我知道有一个技巧可以使用反射更改static final
字段的值,并考虑在Long
上尝试
Field field = Long.class.getField("MIN_VALUE");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, 2);
System.out.println(Long.MIN_VALUE);
但是上面的代码甚至没有抛出任何异常,也没有改变Long.MIN_VALUE
的值。为什么会这样?
答案 0 :(得分:2)
常量原始值直接编译到使用代码中。在运行时,不再访问该字段。因此,之后更改它对使用代码没有任何影响。
我找到的最佳参考是13.4.9 of the JLS部分中的以下段落:
If a field is a constant variable (§4.12.4), then deleting the keyword final or
changing its value will not break compatibility with pre-existing binaries by
causing them not to run, but they will not see any new value for the usage of
the field unless they are recompiled. This is true even if the usage itself is
not a compile-time constant expression (§15.28).