At my org we extensively use @Value.Immutable
annotation with interface
s or abstract class
es to generate Immutable
class
es with builder
s for our internal data transfer objects (DTOs) [ref].
We are writing a new service in Java 17 and want to leverage record
s for DTOs, but we don't want to give up on builder-pattern for construction. We do understand that immutability provided by record
s and builder-pattern are two unrelated concepts, but for our DTOs use-case builder-pattern is absolutely essential
A quick literature survey reveals that as of Sep 2023, the available options for getting builder-pattern out of Java record
s are
Builder
class
nested within Java record
file
@Builder
annotation
Are there any other workarounds of getting builder-pattern with Java records? We are even okay to start-off with hand-written nested builder-classes within records (since both options 2 & 3 make us uneasy), provided our beloved Immutables library starts supporting them in future so that we could seamlessly migrate to them.
We had created an issue [#1484] against Immutables library for this query and as per their response
record
s. Most probably it will be Immutables 3@Builder.Constructor
annotationrecord Uio(
int x,
String b,
boolean z) {
@Builder.Constructor
Uio {
// ...
}
}
var b = new UioBuilder()
.x(4)
.b("xx")
.z(true)
.build();