Reputation: 111
I am using the new Builder.Default feature of Lombok version 1.16.16. I would like to configure a class such that an attribute takes a default value if the attribute is not explicitly set via the builder, or if the attribute is set to null by the builder.
Case 1: Attribute is not set
MyClass.Builder().build();
Case 2: Attribute is set to null
MyClass.Builder().myAttribute(null).build();
In both cases I want a default value to be set. The background is that the class will be built based on the results of a database query.
Below is the annotated class
@Builder
@NonFinal
public class MyClass {
@Builder.Default
private String myAttribute = "-";
}
Is there any way to configure the class such that attributes are set to a default value even if explicitly set to null (Case 2)?
Upvotes: 10
Views: 13631
Reputation: 8734
No, lombok
will not help you there. You set the value
to null
, then this attribute
will be null
.
It's a good idea to look at the generated class
so you can understand how lombok
works.
One workaround come to my mind.
lombok
uses all-args-constructor
to create you class from the BuilderClass
.
So, I think if you create the constructor
by your self and add your logic by checking if this value is null then use the default.
Upvotes: 3