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?
The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.
Lombok's @Builder annotation is a useful technique to implement the builder pattern that aims to reduce the boilerplate code. In this tutorial, we will learn to apply @Builder to a class and other useful features. Ensure you have included Lombok in the project and installed Lombok support in the IDE.
Martin Grajcar. Your @Builder needs an @AllArgsConstructor (add it; feel free to make it private).
When we annotate a class with @Builder, Lombok creates a builder for all instance fields in that class. We've put the @Builder annotation on the class without any customization. Lombok creates an inner static builder class named as StudentBuilder. This builder class handles the initialization of all fields in Student.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With