The below text is from jls http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.3
Even then, there are a number of complications. If a final field is
initialized to a compile-time constant expression (§15.28) in the field
declaration, changes to the final field may not be observed, since uses of that
final field are replaced at compile time with the value of the constant
expression.
Can anyone Please give me better explanation for the above. i couldn't understand the statement changes to the final field may not be observed
. May with the help of example.
Thanks in advance
It means if in a class you have this:
At compile time any reference to
Foo.fooBoolean
may be replaced withtrue
, and references toFoo.fooInt
may be replaced by5
. If at runtime you later change either of those final fields via reflection, the code referencing it (as it was written) may never see it.It tells that , if a final variable is declared as compile time constant then any change made in the final variable using reflection API further in program will not be visible to the program during execution.
For example consider the code given below:
The Output of the above code is:
WHY?
The answer lies in the output provided by
javap -c
command for public static void main:At line 16 (before
changeFinal
method is called)the value ofcf.x
is hardcoded to20
. And at line 33 (afterchangeFinal
method is called) the value ofcf.x
is again hardcoded to20
. Therefore , Although the change in the value of final variablex
is done successfully byreflection API
during execution, but because ofx
being a compile time constant it is showing its constant value20
.