假设我有一个像 Lombok 注释的类
@Builder
class Band {
String name;
String type;
}
我知道我能做到:
Band rollingStones = Band.builder().name("Rolling Stones").type("Rock Band").build();
是否有一种简单的方法可以使用现有对象作为模板创建 Foo 对象并更改其中一个属性?
类似:
Band nirvana = Band.builder(rollingStones).name("Nirvana");
我在 lombok 文档中找不到这个。
最佳答案
您可以使用 toBuilder
参数为您的实例提供 toBuilder()
方法。
@Builder(toBuilder=true)
class Foo {
int x;
...
}
Foo f0 = Foo.builder().build();
Foo f1 = f0.toBuilder().x(42).build();
来自 the documentation :
If using @Builder to generate builders to produce instances of your own class (this is always the case unless adding @Builder to a method that doesn't return your own type), you can use @Builder(toBuilder = true) to also generate an instance method in your class called toBuilder(); it creates a new builder that starts out with all the values of this instance.
免责声明:我是 Lombok 开发者。
关于java - 使用 lombok 从现有对象构建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47069561/