Using Lombok’s @Builder annotation with default values

When writing Java, I’m a big fan of Lombok, a library that helps reduce boilerplate code through code-generation. I’ve written about it in the past, if you’re not familiar with it, checkout my previous posts here and here.

Recently I’ve been confronted with the problem of providing defaults for generated Builder-classes generated by the @Builder annotation. I was expecting that providing default values in the class that @Builder is defined on should be respected when creating instances through a builder, but it turned out that this doesn’t work.

@Builder
public class Person {
  private String firstname = "John";
  private String lastname = "Doe";
}

Instead, what you have to do is provide a minimal Builder implementation containing the default values  and let Lombok fill in the rest:

@Builder
public class Person {
  private String firstname;
  private String lastname;
  private String middleName;
 
  public static class PersonBuilder {
    private String firstname = "John";
    private String lastname = "Doe";
  }
}

Lombok will add any generated code to the existing class and those default values will be respected in the construction process. You can find additional background on this here.

8 thoughts on “Using Lombok’s @Builder annotation with default values

  1. Hi Reinhard,

    nice blog but you can to this better by set the toBuilder to true and the you have a Builder that takes the values of the current bean. In your example:

    @Builder(toBuilder=true)
    @NoArgsConstructor
    @AllArgsConstructor
    public class Person {
    private String firstname = “John”;
    private String lastname = “Doe”;
    }


    Person person = new Person().toBuilder().build();

    • toBuilder() Is a very handy feature, but this way you have to create an extra object before you can use a builder. I like my approach a bit better.

  2. On a side note: if you want your collections to be by default initialized with a size of zero vs defaulting to null, annotate it with @Singular when using @Builder.

  3. That’s great, Thanks.
    It works, but if we use this and use generic type for the class at same time with @Builder, the builder will not work due to accessibility of static class 🙁

    Maybe you have already solution for this issue ?

    Regards

    • I’ve given it a quick shot, I have trouble with the correct resolution of the type parameter. Is that what you mean? If you like, share a gist and I’ll have another look.

Leave a Reply

Your email address will not be published. Required fields are marked *