Lombok 构建器方法 return class 本身的实例而不是 returning 构建器 class

Lombok builder methods return the instance of the class itself instead of returning builder class

我有一个classUser

public class User {
    private String firstName;
    private String lastName;
    private int age;

    public User withFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public User withLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public User withAge(int age) {
        this.age = age;
        return this;
    }
}

所以我可以用User user = new User().withFirstName("Tom").withAge(30);初始化它,user初始化后,我仍然可以用user.withLastName("Bob").withAge(31);修改它。

如何利用 Lombok 来保存 "withXXX" 方法? @Builder 不是为这个用例设计的。

试试这个:

@Data
@Builder
@Accessors(fluent = true) // <— This is what you want
public class User {
    private final String firstName;
    private final String lastName;
    private final int age;
}

然后使用:

User user = User.builder()
    .firstName("foo")
    .lastName("bar")
    .age(22)
    .build();

以后:

user.setFirstName("baz").setAge(23); // fluent setters

请注意如何通过使所有字段 final 使 User 不可变(最佳实践)。如果您想要可变性,请删除 final 关键字。