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 upnullwhen the object is created through the builder; @Builderdoesn't check required fields:build()works even if you never setcustomer;- if you put
@Builderon a JPA entity, Hibernate also needs a no-args constructor (@NoArgsConstructor+@AllArgsConstructor).
For classes with inheritance there is @SuperBuilder.
Sign up to mark studied questions and save your progress.