我偶然发现了一个 friend 发给我的片段。它有一个非常奇怪的行为。我试着用谷歌搜索代码,看看我是否在互联网上找到了一些东西,但没有运气。我联系不上我的 friend ,所以我很好奇它在做什么。
public class Test {
public static void main(String[] args) throws MalformedURLException {
System.out.println(Boolean.TRUE); //This prints false
}
static {
try {
Field value = Boolean.class.getDeclaredField("value");
value.setAccessible(true);
value.set(Boolean.TRUE, value.get(Boolean.FALSE));
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
我认为,就像声明为静态的那段代码一样,它将首先运行 main
方法,并且在该静态代码内部正在更改所有 Boolean
实例(?)。我不知道,我需要专家意见来证实这一点。
最佳答案
Field value = Boolean.class.getDeclaredField("value");
value.setAccessible(true);
value.set(Boolean.TRUE, value.get(Boolean.FALSE));
通过反射将 Boolean.TRUE
的常量值设置为 Boolean.FALSE
。那是..正如您在代码中所读到的那样。
static
初始化程序 block 在 main
方法之前执行,不要让顺序误以为它会在稍后发生。
引自 this帖子:
Assuming no SecurityManager is preventing you from doing this, you can use setAccessible to get around private and resetting the modifier to get rid of final, and actually modify a private static final field.
关于java - 谁能解释一下为什么这段代码返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19371911/