On Tue, 17 Mar 2026 10:36:13 GMT, Burning_TNT <[email protected]> wrote:
>> Alan Bateman has updated the pull request with a new target base due to a >> merge or a rebase. The pull request now contains 63 commits: >> >> - Merge branch 'master' into JDK-8353835 >> - Spurious italics >> - More wordsmithing >> - Improve IAE exception message >> - Merge branch 'master' into JDK-8353835 >> - Cleanup >> - More cleanup of Field.set API docs, including some restructure from Alex >> - Cleanup >> - Merge branch 'master' into JDK-8353835 >> - Update mutateFinals/modules test to exercise exports and opens cases >> - ... and 53 more: https://git.openjdk.org/jdk/compare/8690d263...c3c3cfff > > Hi, with the upcoming changes where modifying final fields of > **non-Serializable** classes will be considered illegal, are there any > alternative approaches to instantiate an object without invoking its > constructors while still initializing its final fields? > > For example, consider the following class: > > public final class Foo { > public final long bar; > > private Foo() { > this.bar = 1; > } > } > > > In previous releases, it was possible to construct an instance like Foo { bar > = 2 } with: > > // Obtain sun.misc.Unsafe#theUnsafe via reflection > Foo foo = theUnsafe.allocateInstance(Foo.class); > // Modify Foo#bar via reflection > barField.set(foo, 2); > > > However, this approach relies on modifying final fields, which is no longer > allowed under the new restrictions. > > I’ve been looking for alternative solutions but haven’t found a viable > replacement so far. > > The JEP mentions: > >> This API allows a serialization library to obtain a [method >> handle](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/invoke/MethodHandle.html) >> to special code that initializes an object by assigning to its instance >> fields directly, including final fields. This code, which is dynamically >> generated by the JDK, gives the serialization library the same powers as the >> JDK's own serialization facilities; it is not necessary to enable final >> field mutation by the module of the serialization library. > > Am I missing something here, or is there currently no supported way to > achieve this? Hi @burningtnt, your comment refers to the ReflectionFactory in jdk.unsupported. This API is intended only to work with serializable classes, so it rejects classes like yours, that are not serializable. There's no plan to support use cases like yours. In fact, there are proposed JIT optimizations that would be broken if we try to dynamically add constructors. Your best alternative is to transform the class files of your desired classes to add new constructors that fulfill your needs. ------------- PR Comment: https://git.openjdk.org/jdk/pull/25115#issuecomment-4075390850
