Lombok: [FEATURE] Allow @Value classes not to be final

Created on 6 Mar 2019  路  7Comments  路  Source: projectlombok/lombok

Using the @Value annotation currently creates a value object with a final class. Effectively, the final modifier's only purpose is to prevent subclassing of that type which is an honorable goal and probably okay in most of the cases. In combination with staticConstructor it's actually not even needed as the constructor generated is turned private anyway and all the user ends up with is a public static factory method anyway.

Why would I want a value object not to be final?

As indicated there are use cases that require subclassing of the types. #892 describes one where user code would do this. However, frameworks might want to create short lived proxies for those types to allow e.g. the application of a method reference for sole invocation recording purposes. E.g. in Spring Data we'd like to provide a Sort abstraction that's supposed to allow the following:

Sort.sort(Person.class).by(Person::getName).asc();

We already have infrastructure in place that creates a proxy for the given type, takes the method reference, executes it on the proxy and in the method interceptor find out about the method that was invoked, the reference invokes to build up the sort expression. This requires a type that we can create a proxy of in the first place.

The code that's generated by @Value creates a type that's effectively immutable anyway as it doesn't expose any means to change state of an instance. So while it's perfectly fine to resort to making that type final by default, it would be cool if the user could opt out of that for convenience reasons

help wanted

Most helpful comment

Hmm, doesn't @NonFinal on the class do exactly this, or am I missing a point here?

All 7 comments

Hmm, doesn't @NonFinal on the class do exactly this, or am I missing a point here?

In fact it does. It just didn't cross my radar as it's in the experimental package and closely aligned with @FieldDefaults, which sort of created the impression it was usable with fields not with types.

I'd be fine with the documentation being updated to mention this more prominently. A boolean flag right within @Value would still be slightly nicer, I guess.

In fact, the javadoc isn't really clear at this point. This should be improved, together with the website documentation on @Value.

The code that's generated by @Value creates a type that's effectively immutable anyway as it doesn't expose any means to change state of an instance.

Yes, but you can add new fields and setters for them in the subclass . So if you want a really immutable class, it must be final. That said, I agree with you.

I welcome a suggestion on how to improve the documentation.

PR integrated :)

Was this page helpful?
0 / 5 - 0 ratings