Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lombok @Builder allow extends

I have 2 classes:

import lombok.Builder;
@Builder
public class B extends A {
}

and

import lombok.Builder;
@Builder
public class A {
}

on the @Builder on B I get the message:

The return type is incompatible with A.builder().

Is this a limitation of lombok? or something I'm doing wrong?

If I leave the @Builder off A, then the Builder on B doesn't seem to consider the fields in A in the constructors for B.

like image 532
AixNPanes Avatar asked Mar 15 '18 14:03

AixNPanes


People also ask

What is the use of @builder annotation in spring boot?

The @Builder annotation produces complex builder APIs for your classes. @Builder lets you automatically produce the code required to have your class be instantiable with code such as: Person. builder()

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 does @builder in Lombok do?

Overview. Project Lombok's @Builder is a helpful mechanism for using the Builder pattern without writing boilerplate code. We can apply this annotation to a Class or a method. In this quick tutorial, we'll look at the different use cases for @Builder.

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.


1 Answers

The latest lombok release 1.18.2 includes the new experimental @SuperBuilder. It supports inheritance and fields from superclasses (also abstract ones). The only requirement is that all superclasses must have the @SuperBuilder annotation. With it, the solution is as simple as this:

@SuperBuilder
public class B extends A {
   private String b;
}

@SuperBuilder
public class A {
    private String a;
}

B instance = B.builder().b("b").a("a").build();
like image 195
Jan Rieke Avatar answered Oct 01 '22 17:10

Jan Rieke