how to Call super constructor in Lombok how to Call super constructor in Lombok java java

how to Call super constructor in Lombok


This is not possible in Lombok. Although it would be a really nice feature, it requires resolution to find the constructors of the super class. The super class is only known by name the moment Lombok gets invoked. Using the import statements and the classpath to find the actual class is not trivial. And during compilation you cannot just use reflection to get a list of constructors.

It is not entirely impossible but the results using resolution in val and @ExtensionMethod have taught us that is it hard and error-prone.

Disclosure: I am a Lombok developer.


Lombok Issue #78 references this page https://www.donneo.de/2015/09/16/lomboks-builder-annotation-and-inheritance/ with this lovely explanation:

@AllArgsConstructor public class Parent {        private String a; }public class Child extends Parent {  private String b;  @Builder  public Child(String a, String b){    super(a);    this.b = b;     } } 

As a result you can then use the generated builder like this:

Child.builder().a("testA").b("testB").build(); 

The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.

I also found this works nicely with Spring Data JPA.


Version 1.18 of Lombok introduced the @SuperBuilder annotation. We can use this to solve our problem in a simpler way.

You can refer to https://www.baeldung.com/lombok-builder-inheritance#lombok-builder-and-inheritance-3.

so in your child class, you will need these annotations:

@Data@SuperBuilder@NoArgsConstructor@EqualsAndHashCode(callSuper = true)

in your parent class:

@Data@SuperBuilder@NoArgsConstructor