Reputation: 10215
I have an Entity
@Builder
class MyEntity {
private Set<OtherEntitiy> children = new HashSet<>()
}
And i get a lombok warning.
warning: @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final. Set = new HashSet<>();
The question is: how can i suppress lombok's warning?
Also. I need to initialize children because i want to avoid NullPointerException. Also i can't mark this filed as final because it is not final really. I cant mark filed @Builder.Default
because i wanna create this entity not only with builder and i wanna to save default value for other constructors.
Upvotes: 31
Views: 29861
Reputation: 6419
Sometimes you just have to write code, so here are a couple more ways of doing this.
@Builder
static class MyEntity {
@NonNull
private Set<MyEntity> children;
}
NullPointerException
is thrown from both the builder and the generated constructor, but with a better message.@NoArgsConstructor
@AllArgsConstructor
@Builder
static class MyEntity {
@NonNull
private Set<MyEntity> children;
}
@AllArgsConstructor
if you use
@NoArgsConstructor
.NullPointerException
is thrown from the builder and both constructors.@Singular
@Builder
class MyEntity {
@Singular
private Set<OtherEntitiy> children;
MyEntity(){
children = new HashSet<>()
}
MyEntity(Set<OtherEntity> children){
this.children = children == null ? new HashSet<> : children;
}
}
@Singular
and @Builder.Default
are not currently compatible.
NullPointerException
is still thrown if the developer passes null to the builder.null
through the
parameterized constructor.null
@Data
@Builder
class MyEntity {
@Singular(ignoreNullCollections = true)
private Set<OtherEntity> children;
MyEntity(){
children = new HashSet<>()
}
MyEntity(Set<OtherEntity> children){
setChildren(children)
}
void setChildren(Set<OtherEntity> children){
this.children = children == null ? new HashSet<>() : children;
}
}
@Singular(ignoreNullCollections = true)
to ignore when developers pass a null reference through the builder.@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder
static class MyEntity {
@Singular(ignoreNullCollections = true)
private Set<MyEntity> children;
}
Notes:
Quietly setting the value when null
is passed instead of throwing a descriptive runtime exception might be more confusing and/or not appropriate for your use cases. Choose the correct approach for your needs.
Upvotes: 0
Reputation: 5399
Use
@Builder.Default
to add default behavior for yourBuilder
@Builder
class MyEntity {
@Builder.Default
private Set<String> children = new HashSet<>();
}
You use it on the field that has a default value defined an Lombok
will then pick up the value during object creation
@Builder.Default
functionality was added in lombok v1.16.16.
So if you're using lower version of Lombok
you will not be able to use it.
Upvotes: 43