Lombok @builder on a class that extends another class

Solution 1:

Since release 1.18.2 lombok includes the new experimental @SuperBuilder. It supports fields from superclasses (also abstract ones). With it, the solution is as simple as this:

@SuperBuilder
public class Child extends Parent {
   private String a;
   private int b;
   private boolean c;
}

@SuperBuilder
public class Parent {
    private double d;
    private float e;
}

Child instance = Child.builder().b(7).e(6.3).build();

Update 2019-10-09: If you use IntelliJ, you need at least version 0.27 of the IntelliJ Lombok plugin to use @SuperBuilder.

PS: @AllArgsConstructor(onConstructor=@__(@Builder)) does not work because @Builder is an annotation-processing annotation that lombok translates to code during compilation. Generating and then translating new lombok annotation would require several iterations of annotation processing, and lombok does not support that. @Autowired, in contrast, is a regular Java annotation available at runtime.

Solution 2:

See in https://blog.codecentric.de/en/2016/05/reducing-boilerplate-code-project-lombok/ (@Builder and inheritance part)

Adjusted to your classes

@AllArgsConstructor
public class Parent {
  private double d;
  private float e;
}

public class Child extends Parent {
  private String a;
  private int b;
  private boolean c;

  @Builder
  public Child(String a, int b, boolean c, double d, float e) {
    super(d, e);
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

With this setup

Child child = Child.builder().a("aVal").b(1000).c(true).d(10.1).e(20.0F).build();

works correctly