I'm using Lombok @Builder
annotation, but I'd like some of the String
fields to be optional and default to ""
to avoid NPEs. Is there an easy way to do this? I can't find anything.
Alternately, a way to customize @Getter
to return a default value if the variable is null
.
Lombok's @Builder annotation is a useful technique to implement the builder pattern that aims to reduce the boilerplate code. In this tutorial, we will learn to apply @Builder to a class and other useful features. Ensure you have included Lombok in the project and installed Lombok support in the IDE.
When we annotate a class with @Builder, Lombok creates a builder for all instance fields in that class. We've put the @Builder annotation on the class without any customization. Lombok creates an inner static builder class named as StudentBuilder. This builder class handles the initialization of all fields in Student.
The @Builder annotation produces complex builder APIs for your classes. @Builder lets you automatically produce the code required to have your class be instantiable with code such as: Person. builder()
Starting from version v1.16.16
they added @Builder.Default
.
@Builder.Default
lets you configure default values for your fields when using@Builder
.
example:
@Setter
@Getter
@Builder
public class MyData {
private Long id;
private String name;
@Builder.Default
private Status status = Status.NEW;
}
PS: Nice thing they also add warning in case you didn't use @Builder.Default
.
Warning:(35, 22) java: @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.
You have to provide the builder class like the below:
@Builder
public class XYZ {
private String x;
private String y;
private String z;
private static class XYZBuilder {
private String x = "X";
private String y = "Y";
private String z = "Z";
}
}
Then the default value for x
, y
, z
will be "X"
, "Y"
, "Z"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With