KeL*_*TaR 4 java reflection spring
我有一个像这样的静态最终字段:
class SomeClass {
static final String CONST = "oldValue";
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试像这样在测试中更改该字段:
ReflectionTestUtils.setField(SomeClass.class, "CONST", "newValue");
Run Code Online (Sandbox Code Playgroud)
但它不起作用并说
java.lang.IllegalStateException: Could not access method: Can not set static final java.lang.String field
Run Code Online (Sandbox Code Playgroud)
强烈建议不要更改静态最终值。
但是如果你真的需要它,你可以使用下面的代码。(仅在(包括)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);
}
Run Code Online (Sandbox Code Playgroud)
编辑
另请注意,您不能更改编译期常量。比如这个HW
public static final String HW = "Hello World".
Run Code Online (Sandbox Code Playgroud)
编译时会内联。
| 归档时间: |
|
| 查看次数: |
8376 次 |
| 最近记录: |