我有一个班级Userpublic 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);useruser.withLastName("Bob").withAge(31);如何利用龙目岛来保存“withXXX”方法?@Builder不是为此用例设计的。
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
试试这个:
@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
注意如何通过使所有字段变得不可变(最佳实践)。如果需要可变性,请删除关键字。Userfinalfinal
添加回答
举报
0/150
提交
取消