如何通过反射,访问父类的private变量。

Field getField(String name)返回已加载类声明的所有public成员变量的Field对象,包括从父类继承过来的成员变量,参数name指定成员变量的名称

而Field getDeclaredField(String name)不能获取从父类那继承过来的成员变量

所以,当A extends B,我们如果仅仅this.getClass().getDeclaredFields();是不可以得到B的field,要这样: this.getClass().getSuperclass().getDeclaredFields();

设置特定对象的field:
A a = new A();
Field f = A.class.getSuperclass().getDeclaredField("name");
f.setAccessible(true);
f.set(a, "nick");
String s = f.get(a);
print(s);

你可能感兴趣的:(java)