标签:
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectionDemo { public static void main(String[] args) throws ClassNotFoundException { String classNameStr ="java.lang.String"; //String classNameStr ="java.lang.Double"; Class<?> cls =Class.forName(classNameStr); Class<?> superCls =cls.getSuperclass(); String modifier =Modifier.toString(cls.getModifiers()); if (modifier.length()>0) { //输出类修饰词 System.out.print(modifier+""); } //输出类名 System.out.print("class "+classNameStr); //输出父类 if (superCls != null && superCls != Object.class) { System.out.print(" extends "+superCls.getName()); } System.out.print("\n{\n"); printConstrctors(cls); System.out.println(); printMethods(cls); System.out.println(); printFields(cls); System.out.println("}"); } /** * 输出属性 * @param cls */ private static void printFields(Class<?> cls) { Field[] fields = cls.getDeclaredFields(); for (Field f : fields) { Class<?> fType = f.getType(); String fName = f.getName(); System.out.print(" "); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length()>0) { System.out.print(modifiers+" "); } System.out.println(fType.getName()+" "+fName+";"); } } /** * 输出方法 * @param cls */ private static void printMethods(Class<?> cls) { Method[] methods = cls.getDeclaredMethods(); for(Method m : methods){ Class<?> retType = m.getReturnType(); String methodName = m.getName(); System.out.print(" "); String modifiers = Modifier.toString(m.getModifiers()); if(modifiers.length()>0){ System.out.print(modifiers+" "); } System.out.print(retType+" "+methodName+"("); Class<?>[] paramTypes = m.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { if (i>0) { System.out.print(", "); } System.out.print(paramTypes[i].getName()); } System.out.println(");"); } } /** * 输出构造函数 * @param cls */ private static void printConstrctors(Class<?> cls) { Constructor<?>[] constructors =cls.getDeclaredConstructors(); for (Constructor<?> c : constructors) { String name = c.getName(); System.out.print(" "); String modifiers =Modifier.toString(c.getModifiers()); if (modifiers.length()>0) { System.out.print(modifiers +" "); } System.out.print(name+"("); Class<?>[] paramTypes = c.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { if (i>0) { System.out.print(", "); } System.out.print(paramTypes[i].getName()); } System.out.println(")"); } } }
标签:
原文地址:http://my.oschina.net/u/1861837/blog/494384