Based on Change private static final field using Java reflectionChange private static final field using Java reflection, I tried to set a private static final field.
(I know this is terribly hacky, but this question is not about code quality; it's about Java reflection.)
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()); // should print 2 } } This prints
1 I've tried this with OpenJDK 6 and 7, and Oracle 7.
I don't know what guarantees Java reflection gives. But if it failed, I thought there would be an Exception (practically all the reflection methods throw exceptions).
What is happening here?