Class c3 = PP.class;
查询成员变量
getFields()只能获取到公共的成员变量 Field[] fields = c3.getFields(); for (Field f : fields) { System.out.println(f.getName()); } getDeclaredFields()获取当前类中所有的成员变量,包含私有的 Field[] fields = c3.getDeclaredFields(); for (Field f:fields) { System.out.println(f.getName()); }
getField只能找到公共的 try { Field name = c3.getField("age"); System.out.println(name.getName()); } catch (NoSuchFieldException e) { System.err.println("没有找到该成员变量"); } getDeclaredField私有的也可以找到 try { Field age = c3.getDeclaredField("age"); System.out.println(age.getName()); } catch (NoSuchFieldException e) { System.err.println("没有找到该成员变量"); }
查询成员方法
查询类中所有的公共的成员方法
Method[] methods = c3.getMethods();
for (Method m:methods) {
System.out.println(m.getName());
}
try {
Method method2 = c3.getMethod("showInfo");
} catch (NoSuchMethodException e) {
System.err.println("该方法没有找到");
}
获取当前类中所有的成员方法,包含私有的
Method[] methods1 = c3.getDeclaredMethods();
for (Method m1 : methods1) {
System.out.println(m1.getName());
}
System.out.println("------------------");
try {
Method showInfo = c3.getDeclaredMethod("showInfo");
System.out.println(showInfo.getName());
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}