简体   繁体   English

Spring ReflectionTestUtils没有设置静态的final字段

[英]Spring ReflectionTestUtils does not set static final field

I have a static final field like this: 我有一个静态的final字段,像这样:

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

and i'm trying to change that field in test like this: 我正在尝试像这样更改测试中的字段:

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

but it doesn't work and says 但它不起作用并说

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

It is highly recommanded do not change a static final value. 强烈建议不要更改静态最终值。

But if you really need it, you can use following code. 但是,如果您确实需要它,则可以使用以下代码。 (Only work before(include) java-8) (仅在(包括)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);
  }

EDIT 编辑

Also notice that you can't change a compile-period constant. 还要注意,您不能更改编译期间常量。 Such as this HW 像这样的HW

public static final String HW = "Hello World".

It will be inline when compile. 编译时将内联。

This works for me. 这对我有用。 Eg we have an object of the following class 例如,我们有以下类的对象

public class LogExample {
     private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
 }

Then in the unit tests we could write like this. 然后在单元测试中,我们可以这样写。 I used org.powermock.reflect.Whitebox and its setInternalState method: 我使用了org.powermock.reflect.Whitebox及其setInternalState方法:

import static org.powermock.reflect.Whitebox.setInternalState;
...
Logger log = mock(Logger.class);
setInternalState(logExample.getClass(), "log", log);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM