使用lombok从现有对象构建对象 [英] Build an object from an existing one using lombok

查看:894
本文介绍了使用lombok从现有对象构建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个lombok注释类,如

Lets say I have a lombok annotated class like

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

我知道我能做到:

Band rollingStones = Band.builder().name("Rolling Stones").type("Rock Band").build();

是否有一种简单的方法可以使用现有对象作为模板创建Foo对象并更改一个它的属性?

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?

类似于:

Band nirvana = Band.builder(rollingStones).name("Nirvana");

我在lombok文档中找不到这个。

I can't find this in the lombok documentation.

推荐答案

您可以使用 toBuilder 参数为您的实例提供 toBuilder()方法。

You can use the toBuilder parameter to give your instances a toBuilder() method.

@Builder(toBuilder=true)
class Foo {
   int x;
   ...
}

Foo f0 = Foo.builder().build();
Foo f1 = f0.toBuilder().x(42).build();

来自文档


如果使用@Builder生成构建器来生成自己类的实例(这总是除非将@Builder添加到不返回自己类型的方法中,否则可以使用@Builder(toBuilder = true)在类中生成一个名为toBuilder()的实例方法;它会创建一个以该实例的所有值开头的新构建器。

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开发人员。

Disclaimer: I am a lombok developer.

这篇关于使用lombok从现有对象构建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆