Java反射應用
阿新 • • 發佈:2019-01-02
bject assm declared struct ger pen red typename print
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); } }
Java反射應用