问题
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