通常情况下,java对象中的属性被指定为static final后,是不能被修改的,但是可以通过下列代码进行修改。
private static void setStaticFinalField(@NotNull Field field, @Nullable Object value) throws IllegalAccessException
{
Field modifiersField;
try {
modifiersField = Field.class.getDeclaredField("modifiers");
}
catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
modifiersField.setAccessible(true);
int nonFinalModifiers = modifiersField.getInt(field) - FINAL;
modifiersField.setInt(field, nonFinalModifiers);
//noinspection UnnecessaryFullyQualifiedName,UseOfSunClasses
sun.reflect.FieldAccessor accessor =
sun.reflect.ReflectionFactory.getReflectionFactory().newFieldAccessor(field, false);
accessor.set(null, value);
}
如果field只是final类型,那么可以先设定field为accessable,
static void ensureThatMemberIsAccessible(@NotNull AccessibleObject classMember)
{
if (!classMember.isAccessible()) {
classMember.setAccessible(true);
}
}
再通过反射进行修改
field.set(targetObject, value);
代码来源:
mockit.internal.util.FieldReflection.setFieldValue(Field, Object, Object)