【Java】How to generate a static factory method with @AllArgsConstructor of Lombok

2024年1月13日

Generating a static factory method with @AllArgsConstructor

@AllArgsConstructor generates an all-args constructor for the class. You can use @AllArgsConstructor as below.

// import

@AllArgsConstructor
public class Book {

    private int id;
    private String name;
    private int price;
}

You can use the generated constructor.

var book1 = new Book(1, "book1", 100);

@AllArgsConstructor generates a static factory method when staticName is specified. In this example, the static factory method “of" is generated.

// import

@AllArgsConstructor(staticName = "of")
public class Book {

    private int id;
    private String name;
    private int price;
}

You can use the factory method as below but you cannot use the constructor because the access level of the constructor is private.

// You can use the generated static factory method.
var book1 = Book.of(1, "book1", 100);

// You cannot use the constructor.
var book2 = new Book(1, "", 10);