How to use Lombok @Builder annotation

For some time now, Lombok provides an annotation for implementing the Builder pattern on your classes. Doing this manually is a good example of Java’s verbosity:

@Getter@EqualsAndHashCode@AllArgsConstructorpublic class Person {  private String firstname;  private String lastname;  private String email;   public static Builder builder() {    return new Builder();  }   public static class Builder {     private String firstname;    private String lastname;    private String email;     public Builder fistname(String firstname) {      this.firstname = firstname;      return this;    }     public Builder lastname(String lastname) {      this.lastname = lastname;      return this;    }     public Builder email(String email) {      this.email = email;      return this;    }     public Person build() {      return new Person(firstname, lastname, email);    }  }}

With every additional property this code will grow significantly. There’s more sophisticated builder implementations that will for example guarantee that mandatory values are set during the construction of an object, but in my experience, most implementations of the builder pattern look like my example above. Let’s see how Lombok helps:

@Getter@EqualsAndHashCode@AllArgsConstructor@Builderpublic class Person {  private final String firstname;  private final String lastname;  private final String email;}

That’s it! One line and you have the same implementation as shown before. There’s some parameters that you can use to customize the generated builder. @Builder(toBuilder=true) will generate a toBuilder() method that will copy the contents of an existent Person instance to a builder, for example. That’s useful if you want to copy and change an object.