Final Variables

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:

import java.lang.reflect.Field;
class Sample {
final int finalInt ;
final String finalString ;

Sample(int a , String s) {
this.finalInt = a;
this.finalString = s;
}
public String toString(){
return(finalInt + " \*\*" + finalString);
}
}

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.

Post a Comment:
Comments are closed for this entry.
About

Hi, I am Vaibhav Choudhary working in Sun. This blog is all about simple concept of Java and JavaFX.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today