Java 使用反射更改Long.MIN_值

Java 使用反射更改Long.MIN_值,java,reflection,static,final,Java,Reflection,Static,Final,我知道有一个技巧可以使用反射来更改静态final字段的值,并考虑在Long上进行尝试 Field field = Long.class.getField("MIN_VALUE"); field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersF

我知道有一个技巧可以使用反射来更改
静态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\u value
的值。为什么会这样?

常量原语值直接编译到使用代码中。在运行时,不再访问该字段。因此,以后更改它对使用代码没有任何影响

我找到的最佳参考是第节的以下段落:


我以前也注意到过类似的行为。Java似乎缓存了原语(和
String
)的最终值,因此通过反射来更改它们通常不起作用。(前面注释的附录)您会发现,如果您通过反射而不是直接访问字段,它将保存更改的值,而不是旧值。
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).