JEP Draft: Prepare to Make Final Mean Final

https://news.ycombinator.com/rss Hits: 19
Summary

Summary Issue warnings about uses of deep reflection to mutate final fields. The warnings aim to prepare developers for a future release that ensures integrity by default by restricting final field mutation; this makes Java programs safer and potentially faster. Application developers can avoid both current warnings and future restrictions by selectively enabling the ability to mutate final fields where essential. Goals Prepare the Java ecosystem for a future release that, by default, disallows the mutation of final fields by deep reflection. As of that release, application developers will have to explicitly enable the capability to do so at startup. Align final fields in normal classes with the components of record classes, which cannot be mutated by deep reflection. Allow serialization libraries to continue working with Serializable classes, even those with final fields. Non-Goals It is not a goal to deprecate or remove any part of the Java Platform API. It is not a goal to prevent the mutation of final fields by serialization libraries during deserialization. Motivation Java developers rely on final fields to represent immutable state. Once assigned in a constructor (for final instance fields) or in a class initializer (for static final fields), a final field cannot be reassigned; its value, whether a primitive value or a reference to an object, is immutable. The expectation that a final field cannot be reassigned in far-flung parts of the program, whether deliberately or accidentally, is often crucial when developers reason about correctness. Furthermore, many classes exist only to represent immutable state, so records were introduced in JDK 16 to provide a concise way to declare a class where all fields are final, making it easy to reason about correctness. The expectation that a final field cannot be reassigned is also important for performance. The more the JVM knows about the behavior of a class, the more optimizations it can apply. For example, being able t...

First seen: 2025-03-31 19:43

Last seen: 2025-04-01 13:46