gpt4 book ai didi

java - 无法使用 java 反射更改静态最终字段?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:07 24 4
gpt4 key购买 nike

我最近偶然发现了 Change private static final field using Java reflection并测试了 polygenelubricants 的 EverythingIsTrue 类,工作正常,System.out.format("Everything is %s", false); 打印 Everything is true 确实。但是当我将代码更改为

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 是否真的有效?

最佳答案

您可以通过将值作为方法调用的结果来避免编译器内联,即使是虚拟调用也是如此。

public class Main {
// value is not known at compile time, so not inlined
public static final boolean FLAG = Boolean.parseBoolean("false");

static void setFinalStatic(Class clazz, String fieldName, Object newValue) throws NoSuchFieldException, IllegalAccessException {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
Field modifiers = field.getClass().getDeclaredField("modifiers");
modifiers.setAccessible(true);
modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}

public static void main(String... args) throws Exception {
System.out.printf("Everything is %s%n", FLAG);
setFinalStatic(Main.class, "FLAG", true);
System.out.printf("Everything is %s%n", FLAG);
}
}

打印

Everything is false
Everything is true

关于java - 无法使用 java 反射更改静态最终字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14102000/

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