Video in progress

What code does Lombok's @Builder annotation actually generate?

@Builder creates a static inner XxxBuilder class inside the class, a setter-style method for every field with the same name, a build() method and a static builder() method. build() calls the all-args constructor.

📖 Answer

@Builder
public class Order {
    private final Long id;
    private final String customer;
    @Builder.Default
    private final String currency = "UZS";
}

After compilation you get roughly this: Order.builder() → OrderBuilder, with .id(..), .customer(..), .currency(..) and .build(), and inside it new Order(id, customer, currency).

Where people go wrong in practice:

  • without @Builder.Default, the initial value in the field ("UZS") ends up null when the object is created through the builder;
  • @Builder doesn't check required fields: build() works even if you never set customer;
  • if you put @Builder on a JPA entity, Hibernate also needs a no-args constructor (@NoArgsConstructor + @AllArgsConstructor).

For classes with inheritance there is @SuperBuilder.