Configuring lombok for builder

断了今生、忘了曾经 提交于 2019-12-23 22:13:09

问题


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?


回答1:


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.




回答2:


By default your IDE cant detect what lombok has generated ,so, to avoid the compilation errors which appear after you added some annotations, i suggest you to install the lombok plugin into your IDE, so you can have your classes generated anc detected by your IDE in real time.



来源:https://stackoverflow.com/questions/55425668/configuring-lombok-for-builder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!