我有一个带有 private static final
字段的类,不幸的是,我需要在运行时更改它。
使用反射我得到这个错误: java.lang.IllegalAccessException: Can not set static final boolean field
有什么办法可以改变价值吗?
Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
原文由 fixitagain 发布,翻译遵循 CC BY-SA 4.0 许可协议
Assuming no
SecurityManager
is preventing you from doing this, you can usesetAccessible
to get aroundprivate
and resetting the modifier to get rid offinal
,实际修改一个private static final
字段。这是一个例子:
假设没有
SecurityException
被抛出,上面的代码打印"Everything is true"
。这里实际做了什么如下:
boolean
valuestrue
andfalse
inmain
are autoboxed to reference typeBoolean
“constants”Boolean.TRUE
和Boolean.FALSE
public static final Boolean.FALSE
引用Boolean
引用Boolean.TRUE
false
is autoboxed toBoolean.FALSE
, it refers to the sameBoolean
as the one refered to byBoolean.TRUE
"false"
现在是"true"
相关问题
static final File.separatorChar
进行单元测试Integer
的缓存,改变String
等的例子注意事项
每当你做这样的事情时,都应该格外小心。它可能不起作用,因为
SecurityManager
可能存在,但即使它不存在,根据使用模式,它也可能起作用,也可能不起作用。也可以看看
private static final boolean
,因为它可以作为编译时常量内联,因此“新”值可能无法观察到附录:关于按位操作
本质上,
从
field.getModifiers()
关闭对应于Modifier.FINAL
的位。&
是按位与,而~
是按位补码。也可以看看
记住常量表达式
仍然无法解决这个问题?,像我一样陷入抑郁症?你的代码看起来像这样吗?
阅读对此答案的评论,特别是@Pshemo 的评论,它提醒我 常量表达式 的处理方式不同,因此 无法 对其进行修改。因此,您需要将代码更改为如下所示:
如果你不是班级的主人……我觉得你!
有关此行为的原因的更多详细信息, 请阅读此 内容?