Java 使用 lombok 从现有对象构建对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47069561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Build an object from an existing one using lombok
提问by Mustafa
Lets say I have a lombok annotated class like
假设我有一个 lombok 注释类,例如
@Builder
class Band {
String name;
String type;
}
I know I can do:
我知道我可以做到:
Band rollingStones = Band.builder().name("Rolling Stones").type("Rock Band").build();
Is there an easy way to create an object of Foo using the existing object as a template and changing one of it's properties?
有没有一种简单的方法可以使用现有对象作为模板来创建 Foo 对象并更改它的一个属性?
Something like:
就像是:
Band nirvana = Band.builder(rollingStones).name("Nirvana");
I can't find this in the lombok documentation.
我在 lombok 文档中找不到这个。
采纳答案by Roel Spilker
You can use the toBuilderparameter to give your instances a toBuilder()method.
您可以使用该toBuilder参数为您的实例提供一个toBuilder()方法。
@Builder(toBuilder=true)
class Foo {
int x;
...
}
Foo f0 = Foo.builder().build();
Foo f1 = f0.toBuilder().x(42).build();
From 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.
如果使用@Builder 生成构建器来生成您自己的类的实例(除非将@Builder 添加到不返回您自己的类型的方法中,否则总是如此),您还可以使用@Builder(toBuilder = true) 来生成你的类中的一个实例方法叫做 toBuilder(); 它创建一个新的构建器,以该实例的所有值开始。
Disclaimer: I am a lombok developer.
免责声明:我是龙目岛的开发人员。
回答by maaartinus
Is there an easy way to create an object of Foo using the existing object as a template and changing oneof it's properties? (emphasis mine)
有没有一种简单的方法使用现有对象作为模板,改变创建的Foo对象一个它的属性?(强调我的)
If you really want to change a single property, then there's a nicer and more efficient way:
如果您真的想更改单个属性,那么有一种更好、更有效的方法:
@With
class Band {
String name;
String type;
}
Band nirvana = rollingStones.withName("Nirvana");
The wither creates no garbage, but it can change just a single field. For changing many fields, you could use
凋灵不会产生垃圾,但它只能改变一个领域。要更改许多字段,您可以使用
withA(a).withB(b).withC(c)....
and produce tons of garbage (all intermediate results) but than toBuilderis more efficient and more natural.
并产生大量垃圾(所有中间结果),但toBuilder效率更高,更自然。
NOTE: Older versions of lombok have used @Witherannotation. See beginning of documentation.
注意:旧版本的 lombok 使用了@Wither注释。请参阅文档开头。

