java - 使用 lombok 从现有对象构建对象

标签 java lombok

假设我有一个像 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/

相关文章:

java-8 - 来自 lombok 和 mapstruct 的@Accessors(fluent = true)

java - Lombok注释在Intellij idea下无法编译

java - 托管多个基于 tomcat 的 Web 应用程序时,最佳做法是什么

java - JVM 不能使用大页面内存,因为它没有足够的权限将页面锁定在内存中

java - 如何在自定义标签中使用doTag方法添加cookie?

java - 使用构建器时无法执行自定义反序列化

java - 从资源目录获取文件进行单元测试,但获取产品的绝对路径

java - 错误: Not detached model found

java - 创建具有相同值的多个对象时重用构建器实例是否可以接受?

java - 由于 lombok 创建的非默认构造函数,Jackson 反序列化失败