获取域值:
Class cl = new Animal().getClass();
try {
//获取所有字段
Field[] fields = cl.getDeclaredFields();
for (Field f : fields) {
//设置可以访问私有域
f.setAccessible(true);
System.out.println(f.get(new Animal()));
}
} catch (Exception e) {
// TODO: handle exception
}
方法调用
public static void main(String[] args) {
Animal an = new Animal();
Class cl = an.getClass();
try {
Method method = cl.getDeclaredMethod("setName", String.class);
method.invoke(an, "张三");
Field f = cl.getDeclaredField("name");
f.setAccessible(true);
System.out.println(f.get(an));
} catch (Exception e) {
// TODO: handle exception
}
}