通过反射更改私有最终字段
2022-08-31 20:13:22
class WithPrivateFinalField {
private final String s = "I’m totally safe";
public String toString() {
return "s = " + s;
}
}
WithPrivateFinalField pf = new WithPrivateFinalField();
System.out.println(pf);
Field f = pf.getClass().getDeclaredField("s");
f.setAccessible(true);
System.out.println("f.get(pf): " + f.get(pf));
f.set(pf, "No, you’re not!");
System.out.println(pf);
System.out.println(f.get(pf));
输出:
s = I’m totally safe
f.get(pf): I’m totally safe
s = I’m totally safe
No, you’re not!
为什么它以这种方式工作,你能解释一下吗?第一个打印件告诉我们,私有的“s”字段没有像我预期的那样被更改。但是,如果我们通过反射获得字段,则第二个打印显示,它将被更新。