gpt4 book ai didi

java - 使用反射更改 Long.MIN_VALUE

转载 作者:行者123 更新时间:2023-11-30 04:15:28 25 4
gpt4 key购买 nike

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

最佳答案

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

我找到的最佳引用是 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).

关于java - 使用反射更改 Long.MIN_VALUE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18512941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com