简体   繁体   中英

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;

    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:)

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 both in parent and in child class.

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 still part of lombok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM