Oracle Blog

Java + JavaFX + World

Saturday Mar 22, 2008

It can be little surprising but final variables can be changed from JDK 1.5 onwards. How ? Via reflection API. I still need to dig more into the code, off course OpenJDK code :) to see how it is possible. Here is a small code to see how final variable can be changed with reflection API:

public class FinalTest {public static void changeFinal(Sample f, String finalString, Object value)throws NoSuchFieldException, IllegalAccessException {Field field = Sample.class.getDeclaredField(finalString);field.setAccessible(true);field.set(f, value);}public static void main(String[] args)throws Exception {Sample ft = new Sample(10,"Hello World");changeFinal(ft,"finalString","Hello");System.out.println(ft);}}Searching little on Web explained me that this behavior is not consistent throughout. JDK1.2 used to give the same output for this code, whereas JDK 1.3 and 1.4 throws IllegalAccessException. And now again JDK 1.5, you can change the variable. I will try to see more on this part.