[英]Lombok builder methods return the instance of the class itself instead of returning builder class
我有一個類User
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);
修改它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
注意如何User
可以通過使所有領域進行不可變的(最佳實踐), final
。 如果你想變性,除去final
關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.