Java反射应用
public static void main(String[] args) { Integer i = 0; printClassMessage(i); } private static void printClassMessage(Object obj) { Class c = obj.getClass(); System.out.println("类的名字是:"); System.out.println(c.getName()); //成员变量 System.out.println("------------------------"); System.out.println("类的成员变量是:"); Field[] fs = c.getDeclaredFields(); for(Field f: fs) { Class fieldType = f.getType(); String typeName = fieldType.getName(); String fieldName = f.getName(); System.out.println(typeName+" "+fieldName); } //构造函数 System.out.println("------------------------"); System.out.println("类的构造函数是:"); Constructor[] cts = c.getDeclaredConstructors(); for(Constructor ct : cts) { String value = ""; value += ct.getName() + "("; Class[] paramTypes = ct.getParameterTypes(); for(Class param: paramTypes) { value += param.getName() + ","; } if (value.endsWith(",")) { value = value.substring(0,value.length()-1); } value += ")"; System.out.println(value); } //内部方法 System.out.println("------------------------"); Method[] ms = c.getMethods(); System.out.println("类的内部方法是:"); for(int i=0;i<ms.length;i++) { String value = ""; Class returnType = ms[i].getReturnType(); value += returnType.getName() + " "; value += ms[i].getName() + "("; Class[] paraTypes = ms[i].getParameterTypes(); for(Class c1 : paraTypes) { value += c1.getName() + ","; } if (value.endsWith(",")) { value = value.substring(0,value.length()-1); } value += ")"; System.out.println(value); } }