Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implements Lombok @Builder for Abstract class

Tags:

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?

like image 294
sam Avatar asked Jul 06 '18 10:07

sam


People also ask

What is difference between @builder and @SuperBuilder?

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.

What is @builder annotation in Lombok?

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.

Does @builder require AllArgsConstructor?

Martin Grajcar. Your @Builder needs an @AllArgsConstructor (add it; feel free to make it private).

What does @builder do in Lombok?

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.


1 Answers

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(); 
like image 94
Jan Rieke Avatar answered Sep 19 '22 23:09

Jan Rieke