简体   繁体   中英

Inheritance for builders in lombok

I was trying to use lombok for my project.

I have a class A:

@Data
@Builder
public class A {
    Integer a1;
}

and a class B:

@Data
public class B extends A {
    Integer b1;

    @Builder
    public B(Integer b1, Integer a1) {
        super(a1);
        this.b1 = b1;
    }
}

I am getting an error saying builder() in B cannot override builder() in A, as return type in BBuilder is not compatible with return type in ABuilder.

Is there some way to do this using lombok? I do not want to write the complete builder for for B, unless I don't have any other option.

PS: I have given explicit constructor for class B due to Issue . I tried searching, but I could not find a good solution for the same.

Here we just need to call super of the builder.

@Data
public class B extends A {
    Integer b1;

    @Builder
    public B(Integer b1, Integer a1) {
        super(a1);
        this.b1 = b1;
    }

    public static class BBuilder extends ABuilder{
            BBuilder() {
                super();
            }
    }
}

If you are using Lombok 1.18.4 along with IntelliJ, following code shall work for you:

@Data
@Builder
class A {
    Integer a1;
}

@Data
class B extends A {
    Integer b1;

    @Builder (builderMethodName = "BBuilder")
    public B(Integer b1, Integer a1) {
        super(a1);
        this.b1 = b1;
    }
}

public class Main {

    public static void main(String[] args){
    System.out.println(B.BBuilder().a1(1).b1(1).build());

    }
}

One a side note, @SuperBuilder annotation didn't work in IntelliJ at time of writing this answer. If you have multiple level of inheritance, please avoid Lombok or it will make your Java models messy.

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

Please use lombok version: 1.18.2, @SuperBuilder annotations in child/parent class

If your parent class already has @Builder , then your child should be marked with @SuperBuilder .

Having both parent and child as @Builder won't work.

Parent class A:

@Data
@Builder
public class A {
    Integer a1;
}

Child class B:

@Data
@SuperBuilder
public class B extends A {
    Integer b1;
}

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