Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default field value with @Builder or @Getter annotation in Lombok

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.

like image 679
Hazel Troost Avatar asked Oct 28 '16 23:10

Hazel Troost


People also ask

What is @builder annotation in Lombok?

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.

What does @builder do in Lombok?

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.

What is the use of @builder annotation in spring boot?

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


2 Answers

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.

like image 100
JafarKhQ Avatar answered Oct 21 '22 19:10

JafarKhQ


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".

like image 29
ntalbs Avatar answered Oct 21 '22 20:10

ntalbs