简体   繁体   中英

Configuring lombok for builder

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;

}

then your code can be :

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

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?

You can use it like this:

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

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.

默认情况下,您的 IDE 无法检测 lombok 生成的内容,因此,为了避免添加一些注释后出现的编译错误,我建议您将 lombok 插件安装到您的 IDE 中,以便您的 IDE 可以检测到您生成的类实时。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM