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

Build an object from an existing one using lombok

假设我有一个 lombok 注释 class 喜欢

@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 开发者。

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? (emphasis mine)

如果你真的想换一个属性,那么有一个更好更高效的方法:

@With
class Band {
   String name;
   String type;
}

Band nirvana = rollingStones.withName("Nirvana");

凋灵不会产生垃圾,但它只能改变一个领域。要更改许多字段,您可以使用

withA(a).withB(b).withC(c)....

并产生大量垃圾(所有中间结果),但比 toBuilder 更高效、更自然。

注意:旧版本的 lombok 使用了 @Wither 注释。参见 beginning of documentation

您可能还想使用 com.fasterxml.jackson.databind.ObjectMapper

复制对象
@AllArgsConstructor
@Setter
class Band {
    String name;
    String type;
}

ObjectMapper objectMapper = new ObjectMapper(); //it's configurable
objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false );
objectMapper.configure( SerializationFeature.FAIL_ON_EMPTY_BEANS, false );

Band rollingStones = new Band("Rolling Stones", "Rock Band");

Band nirvana = objectMapper.convertValue( rollingStones, Band.class);
nirvana.setName("Nirvana");

它可以很容易地包装在一些实用方法中,以便在整个项目中使用,例如 ConvertUtils.clone(rollingStones, Band.class)