How to implements Lombok @Builder for Abstract class

做~自己de王妃 提交于 2020-02-24 04:37:32

问题


I have classes that extend an abstract class and I don't want to put @Builder on top of the all child classes.

Is there any way to implement Lombok @Builder for an abstract class?


回答1:


Not possible at all. The builder is generated into the super class during compiling and it can not have any knowledge of the possible sub classes that will eventually implement it.

For example, the sub class could have constructors that have to be used for the instance to have a valid state and Lombok can not have any knowledge about it when the builder is generated.

Take a look at the example code in @Builder documentation. You'll quickly see that it is just impossible to adapt it into instantiating an unknown sub class.




回答2:


This is possible with lombok 1.18.2 (and above) using the new (experimental) annotation @SuperBuilder. The only restriction is that every class in the hierarchy must have the @SuperBuilder annotation. There is no way around putting @SuperBuilder on all subclasses, because Lombok cannot know all subclasses at compile time. See the lombok documentation for details.

Example:

@SuperBuilder
public abstract class Superclass {
    private int field1;
}

@SuperBuilder
public class Subclass extends Superclass {
    private int field2;
}

Subclass instance = Subclass.builder().field1(1).field2(2).build();


来源:https://stackoverflow.com/questions/51208842/how-to-implements-lombok-builder-for-abstract-class

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