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

use*_*386 5 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 = "-";

}
Run Code Online (Sandbox Code Playgroud)

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

Jaf*_*KhQ 3

不,lombok不会在那里帮助你。你设置valuenull,那么这attribute就是null

查看生成的内容是个好主意,class这样您就可以了解lombok其工作原理。

我想到了一种解决方法。
lombok用于all-args-constructorBuilderClass.

constructor 因此,我认为如果您自己创建并通过检查该值是否为空来添加逻辑,则使用默认值。