为构建器配置lombok [英] Configuring lombok for builder

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

问题描述

我想避免使用多个构造函数,所以我想使用构建器设计模式,通过使用 lombok 库,它可以更加容易,所以我想用该库注释:

I want to avoid multiple constructors, so I want to use a builder design pattern, by using lombok library, it can be more easier, so I want to annotate class of ContractDTO with this library annotation:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
class ContractDTO {

    private Integer id;  
    private String name;
    private Integer acquirerId;    
    private Integer terminalId;    
    private String merchantId;

}

那么您的代码可以是:

...
.map(g -> new ContractDTO().toBuilder()
        .name(g.getName())
        .merchantName(g.getMerchantId())
        .build()
)....

但是当我尝试编译代码时,我找不到符号 [错误]符号:toBuilder()方法

But when I try to compile the code I get cannot find symbol [ERROR] symbol: method toBuilder()

可能我需要提前生成代码?

Probably I need to generate the code in advance?

推荐答案

您可以像这样使用它:

 ContractDTO.builder()
    .name(g.getName())
    .merchantName(g.getMerchantId())
    .build();

如果要创建对象的副本或近似副本,可以将属性toBuilder = true添加到@Builder批注.这告诉Lombok向我们的Class添加一个toBuilder()方法.当我们调用toBuilder()方法时,它将返回一个构建器,该构建器使用其调用实例的属性进行初始化.

If we want to create copies or near-copies of objects, we can add the property toBuilder = true to the @Builder annotation. This tells Lombok to add a toBuilder() method to our Class. When we invoke the toBuilder() method, it returns a builder initialized with the properties of the instance it is called on.

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

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