我使用lombok project的@Builder,所以請(qǐng)考慮我有這個(gè)例子:
@Builder
public class Client {
private @Getter @Setter Integer id;
private @Getter @Setter String name;
}
這相當(dāng)于:
public class Client {
private @Getter @Setter Integer id;
private @Getter @Setter String name;
public static class Builder {
private Integer id;
private String name;
private Builder() {
}
public Builder id(final Integer value) {
this.id = value;
return this;
}
public Builder name(final String value) {
this.name = value;
return this;
}
public Client build() {
return new Client(this);
}
}
public static Client.Builder builder() {
return new Client.Builder();
}
private Client(final Builder builder) {
this.id = builder.id;
this.name = builder.name;
}
}
當(dāng)我嘗試一次性設(shè)置所有字段時(shí)沒有問題:
public static void main(String[] args) {
Client client = Client.builder()
.id(123)
.name("name")
.build();
}
輸出:
Client{id=123, name=name}
現(xiàn)在,考慮我想要多次拍攝.例如:
public static void main(String[] args) {
Client client = Client.builder()
.id(123)//<-------------------------- Set just the id
.build();
client = Client.builder()
.name("name")//<--------------------- Set name
.build();
}
這在邏輯上為id返回null:
Client{id=null, name=name}
通常,沒有l(wèi)ombok,我通過在Builder類中添加一個(gè)新的構(gòu)造函數(shù)來解決這個(gè)問題,該構(gòu)造函數(shù)采用相同的對(duì)象:
public static class Builder {
// ...
public Builder(Client client) {
this.id = client.id;
this.name = client.name;
}
// ...
}
然后我將我的對(duì)象傳遞給該構(gòu)造函數(shù):
Client client = Client.builder()
.id(123)
.build();
client = new Client.Builder(client)//<---------------- Like this
.name("name")
.build();
這解決了我的問題,但我不能用lombok來解決它.有什么方法可以解決這個(gè)問題嗎? 解決方法: 您可以使用toBuilder屬性來執(zhí)行此操作.
@Builder(toBuilder=true)
public class Client {
private @Getter @Setter Integer id;
private @Getter @Setter String name;
}
然后你可以這樣使用它
public void main(String[] args){
Client client = Client.builder()
.id(123)
.build();
client = client.toBuilder()
.name("name")
.build();
}
來源:https://www./content-1-335051.html
|