对于类A、B,A是B的基类,A有一个私有成员name
A.java
public class A { private String name = "A"; public void print() { System.out.println(name); }}
B.java
public class B extends A {}
对于A对象a,要想改变a的name,可以这样操作:
try { Field nameFieldInA = a.getClass().getDeclaredField("name"); nameFieldInA.setAccessible(true); nameFieldInA.set(a, "一"); a.print(); } catch (NoSuchFieldException | IllegalAccessException ex) { ex.printStackTrace(); }
要访问a的name,可执行nameFieldInA.get(a)
对于B对象b,要改变b的name,可以这样:
import java.lang.reflect.Field;public class Main { public static void main(String[] args) { try { B b = new B(); b.print(); Field field = b.getClass().getSuperclass().getDeclaredField("name"); field.setAccessible(true); field.set(b, "B"); b.print(); } catch (NoSuchFieldException | IllegalAccessException ex) { ex.printStackTrace(); } }}