Xi Minghui
Xi Minghui

Reputation: 390

How to use Lombok to create a constructor that calls AllArgsConstructor of super class?

I have a super class and child class:

@Data
@AllArgsConstructor
public class Parent {

    private String name;

}
@Data
public class Child extends Parent {

    private int age;

    // I want Lombok to create an equivalent constructor.
    public Child(String name, int age) {
        super(name);
        this.age = age;
    }

}

How can I use Lombok annotation to help me create child class constructor?

Thanks in advance :)

Upvotes: 12

Views: 12721

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18909

As of lombok version 1.18.2, you can use for this reason the @SuperBuilder annotation.

@Data
@AllArgsConstructor
@SuperBuilder
public class Parent {

    private String name;

}
@Data
@SuperBuilder
public class Child extends Parent {

    private int age;
}

Keep in mind that the annotation needs to be in both the parent and the child classes.

Then you can use it as Child child = Child.builder().age(1).name("Mike").build()

As written in the doc

@SuperBuilder generates a protected constructor on the class that takes a builder instance as a parameter. This constructor sets the fields of the new instance to the values from the builder.

Official documentation

As explained in the documentation, this does not exactly generate what the question asks,

          public Child(String name, int age) {
            super(name);
            this.age = age;
        }

But it creates instead a constructor that takes a builder as parameter and from this builder and the parameters it contains it moves forward to instantiating both fields in parent and child class. But this is the only possible solution with lombok as to use a constructor from the child class to instantiate fields both in parent and child class.

Keep in mind that this was added as an experimental feature 4 years ago and it's still part of lombok.

Upvotes: 4

Related Questions