Spring ReflectionTestUtils does not set static final field
10,360
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)
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
public static final String HW = "Hello World".
It will be inline when compile.
Author by
KeLsTaR
Updated on July 01, 2022Comments
-
KeLsTaR over 1 year
I have a static final field like this:
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