This answer is more than exhaustive on this topic.
JLS 17.5.3 Subsequent Modification of Finite Fields
Even then, there are a number of complications. If the final field is initialized with a compile-time constant in the field declaration, changes to the final field may not be observed, since the use of this final field is replaced at compile time with a compile-time constant.
But, if you carefully read the paragraph above, you can find a way here (set the private final field in the constructor instead of the field definition):
import java.lang.reflect.Field; public class Test { public static void main(String[] args) throws Exception { WithPrivateFinalField pf = new WithPrivateFinalField(); System.out.println(pf); Field f = pf.getClass().getDeclaredField("s"); f.setAccessible(true); System.out.println("f.get(pf): " + f.get(pf)); f.set(pf, "No, you're not!"); System.out.println(pf); System.out.println("f.get(pf): " + f.get(pf)); } private class WithPrivateFinalField { private final String s; public WithPrivateFinalField() { this.s = "I'm totally safe"; } public String toString() { return "s = " + s; } } }
The output is as follows:
s = I'm totally safe f.get(pf): I'm totally safe s = No, you're not! f.get(pf): No, you're not!
Hope this helps a bit.
Jiri Patera Dec 23 '10 at 7:14 2010-12-23 07:14
source share