我最近偶然发现了Change private static final field using Java reflection和测试的polygenelubricants'EverythingIsTrue
类,工作正常,System.out.format("Everything is %s", false);
打印Everything is true
确实。但是,当我改变代码为无法使用java反射更改静态最终字段?
public class EverythingIsTrue {
public static final boolean FALSE = false;
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void main(String[] args) throws Exception {
setFinalStatic(EverythingIsTrue.class.getField("FALSE"), true);
System.out.format("Everything is %s", FALSE);
}
}
它打印
Everything is false
有谁知道为什么吗? setFinalStatic实际上是否工作?
这是完全一样的答案,因为我的 - 只能用更多的话! – dty
@dty它看起来像是无限的更多的单词;) –
我删除了我的答案,因为你的答案已经被接受了,而我的答案并没有增加任何价值 - 只是简洁! ;-) – dty