39

Lombok @Builder doesn't work for inheritance use cases:

For example

class Foo{
 protected int xyz1;
 .....
 protected String xyz7;
}


class Bar extends Foo{

}

For given use case Lombok will not be able to generate methods to set value of parameter defined in Foo class.

A workaround for this is:

  1. Manual creating constructor of Bar.
  2. Putting a Builder annotation on that constructor.

Is there a better workaround ?

Vivek Goel
  • 22,942
  • 29
  • 114
  • 186

3 Answers3

52

Lombok has introduced experimental features with version: 1.18.2 for inheritance issues faced with Builder annotation, and can be resolved with @SuperBuilder annotation as below.

@SuperBuilder
public class ParentClass {
    private final String a;
    private final String b;
}

@SuperBuilder
public class ChildClass extends ParentClass{
    private final String c;
}

Now, one can use Builder class as below (that was not possible with @Builder annotation)

ChildClass.builder().a("testA").b("testB").c("testC").build();
Amit Kaneria
  • 5,466
  • 2
  • 35
  • 38
20

I leave this here for reference, as other answers demonstrate there is now (not at the time this answer was posted) a @SuperBuilder feature available now in the library which seems more fitting.

It´s a bit hidden, but people have had this question before, see:

https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/

To summarise the blog post

@AllArgsConstructor
public class Parent {
  private String a;
}

public class Child extends Parent {

  private String b;

  @Builder
  private Child(String a, String b){
    super(a);
    this.b = b;
  }
}

Would allow you to use

Child.builder().a("testA").b("testB").build()
fd8s0
  • 1,897
  • 1
  • 15
  • 29
  • 1
    well don't blame me! that's as much support as there is unless somebody improves the library – fd8s0 Jan 19 '17 at 16:34
  • I couldn't get this to work with more than one layer of inheritance. But @Anamika's answer with `@SuperBuilder` worked for me. – djsmith Dec 09 '19 at 23:14
  • I moved my edit comment to the top of the answer, this answer is older than the @SuperBuilder feature. – fd8s0 Dec 12 '19 at 10:26
0

There is a solution to this problem currently in the works. Check the progress here: https://github.com/rzwitserloot/lombok/pull/1337

Jacques Koorts
  • 1,819
  • 1
  • 17
  • 10