lombok-多张照片中的@Builder模式 [英] lombok - @Builder pattern in multiple shots
问题描述
我使用 lombok项目的@Builder
,所以请考虑我有以下示例:
I use @Builder
of lombok project, so consider I have this example:
@Builder
public class Client {
private @Getter @Setter Integer id;
private @Getter @Setter String name;
}
等同于:
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;
}
}
当我一次尝试设置所有字段时,没有问题:
When I try to set all the the fields in one shot there are no problem:
public static void main(String[] args) {
Client client = Client.builder()
.id(123)
.name("name")
.build();
}
输出:
Client{id=123, name=name}
现在,考虑我要多次拍摄.例如:
Now, consider I want to make it in multiple shots. For example:
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}
通常,没有lombok,我通过在Builder
类中添加一个带有相同对象的新构造函数来解决此问题:
Generally, without lombok, I solve this issue with adding a new constructor in the Builder
class which take the same object:
public static class Builder {
// ...
public Builder(Client client) {
this.id = client.id;
this.name = client.name;
}
// ...
}
然后我将对象传递给该构造函数:
Then I pass my object to that constructor:
Client client = Client.builder()
.id(123)
.build();
client = new Client.Builder(client)//<---------------- Like this
.name("name")
.build();
这解决了我的问题,但是我无法用龙目岛解决它.有什么办法可以解决这个问题?
This solves my issue, but I can't arrive to solve it with lombok. Is there any way to solve this issue?
推荐答案
您可以使用toBuilder
属性执行此操作.
You can use the toBuilder
property to do that.
@Builder(toBuilder=true)
public class Client {
private @Getter @Setter Integer id;
private @Getter @Setter String name;
}
然后您可以像这样使用它
and then you can use it like that
public void main(String[] args){
Client client = Client.builder()
.id(123)
.build();
client = client.toBuilder()
.name("name")
.build();
}
这篇关于lombok-多张照片中的@Builder模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!