gpt4 book ai didi

java - Spring ReflectionTestUtils 未设置静态最终字段

转载 作者:行者123 更新时间:2023-12-01 06:03:27 30 4
gpt4 key购买 nike

我有一个像这样的静态最终字段:

class SomeClass {
static final String CONST = "oldValue";
}

我正在尝试在测试中更改该字段,如下所示:

ReflectionTestUtils.setField(SomeClass.class, "CONST", "newValue");

但它不起作用并显示

java.lang.IllegalStateException: Could not access method: Can not set static final java.lang.String field

最佳答案

强烈建议不要更改静态最终值。

但是如果你真的需要它,你可以使用下面的代码。 (仅适用于(包括)java-8之前)

  static void setFinalStatic(Field field, Object newValue) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
field.setAccessible(true);

Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

field.set(null, newValue);
}

编辑

另外,请注意您无法更改编译期常量。比如这个HW

public static final String HW = "Hello World".

编译时它将是内联的。

关于java - Spring ReflectionTestUtils 未设置静态最终字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51521837/

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