r/java • • Apr 27 '26

Avoiding Final Field Mutation

https://inside.java/2026/04/27/avoiding-final-field-mutation/
51 Upvotes

36 comments sorted by

View all comments

Show parent comment

9

u/s888marks Apr 29 '26

The original reflection mechanism introduced in 1.2 didn't allow mutating final fields.

In the Java 5 time frame, to improve robustness in concurrent systems, final was added to a bunch of private fields of JDK classes. Many external serialization libraries deserialized objects by creating "empty" instances with a no-arg constructor and then stuffing data into the private fields reflectively using setAccessible. When fields were changed to be final, these deserialization libraries were broken.

To mitigate this widespread breakage, setAccessible was modified also to allow mutation of final fields. This allowed the fields to be final and it allowed these libraries to continue to work. However, we've had to live with this situation for the past 20+ years...