public static void reflect(Object e) throws Exception {
Class<? extends Object> cls = e.getClass();
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
f.setAccessible(true);
System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(e));
}
}
public static void reflectMeth() {
Person p = new Person();
Class<? extends Object> clazz = p.getClass();
try {
// 调用指定的方法
/*
* Method m = clazz.getDeclaredMethod("getName", String.class);
* m.invoke(clazz.newInstance(),"参数");
*/
// 获取所有的方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
method.invoke(p);
}
} catch (Exception e) {
e.printStackTrace();
}
}
参考:java反射获取和调用方法