Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lombok set default value when an attribute is explicity set to null by builder

Tags:

lombok

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)?

like image 496
user7981386 Avatar asked Oct 30 '22 08:10

user7981386


1 Answers

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.

like image 169
JafarKhQ Avatar answered Nov 09 '22 12:11

JafarKhQ