Based on Change my personal static final field using Java reflection , I tried to set my personal static final field.
(I know this is terribly hacked, but this question is not about the quality of the code, but the reflection of Java.)
import java.lang.reflect.Field; import java.lang.reflect.Modifier; class Main { static class Foo { private static final int A = 1; int getA() { return A; } } public static void main(String[] args) throws Exception { Field modifiers = Field.class.getDeclaredField("modifiers"); modifiers.setAccessible(true); Field field = Foo.class.getDeclaredField("A"); field.setAccessible(true); modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, 2); System.out.println(new Foo().getA());
Will print
1
I tried this with OpenJDK 6 and 7 and Oracle 7.
I do not know what the Java guarantee gives. But if this failed, I thought there would be an Exception (almost all reflection methods throw exceptions).
What's going on here?
source share