I tried to modify private final static variable like this:
...try {
Field f =TargetA.class.getDeclaredField("RECV_TIMEOUT");
f.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(f, f.getModifiers() & ~Modifier.FINAL);
f.set(null, 12L);
} catch (Exception e) {
e.printStackTrace();//not reach here!
} ...
class TargetA{
private static final long RECV_TIMEOUT = 180000L;
}
However TargetA.RECV_TIMEOUT is still 180000L, without any Exception.
I searched the problem in StackOverflow, but couldn’t find solution.
I guess the Java version1.6 has more restriction in reflection which breaks OO rules.
Thanks for your advice!
You can change the static final field this way and if you look at the value using reflection it will be changed. The problem you have is that the compiler does one and only one optimisation which is to inline constants know at compile time. This means the value can be change, however the places where the constant is used is not changed.
A way around this is to use a wrapper method to “confuse” the compiler, which avoid having to change how you use the constant.