I recently stumbled upon Change private static final field using Java reflection and tested polygenelubricants' EverythingIsTrue
class, works fine, System.out.format("Everything is %s", false);
prints Everything is true
indeed. But when I change the code as
public class EverythingIsTrue {
public static final boolean FALSE = false;
static void setFinalStatic(Field field, Object newValue) throws Exception {
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
public static void main(String[] args) throws Exception {
setFinalStatic(EverythingIsTrue.class.getField("FALSE"), true);
System.out.format("Everything is %s", FALSE);
}
}
it prints
Everything is false
Does anybody know why? Does setFinalStatic actually work or not?