简体   繁体   English

龙目岛建设者的继承

[英]Inheritance for builders in lombok

I was trying to use lombok for my project.我试图在我的项目中使用 lombok。

I have a class A:我有一个A类:

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

and a class B:和 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.我收到一条错误消息,说 B 中的 builder() 不能覆盖 A 中的 builder(),因为 BBuilder 中的返回类型与 ABuilder 中的返回类型不兼容。

Is there some way to do this using lombok?有没有办法使用 lombok 来做到这一点? I do not want to write the complete builder for for B, unless I don't have any other option.我不想为 B 编写完整的构建器,除非我别无选择。

PS: I have given explicit constructor for class B due to Issue . PS:由于问题,我已经为 B 类提供了显式构造函数。 I tried searching, but I could not find a good solution for the same.我尝试搜索,但找不到相同的好的解决方案。

Here we just need to call super of the builder.这里我们只需要调用builder的super即可。

@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:如果您将 Lombok 1.18.4 与 IntelliJ 一起使用,以下代码将适用于您:

@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.一个旁注,@SuperBuilder 注释在撰写此答案时在 IntelliJ 中不起作用。 If you have multiple level of inheritance, please avoid Lombok or it will make your Java models messy.如果您有多层继承,请避免使用 Lombok,否则它会使您的 Java 模型变得混乱。

Lombok has introduced experimental features with version: 1.18.2 for inheritance issues faced with Builder annotation, and can be resolved with @SuperBuilder annotation Lombok 在 version: 1.18.2 中引入了实验性功能,用于 Builder 注解面临的继承问题,可以通过 @SuperBuilder 注解解决

Please use lombok version: 1.18.2, @SuperBuilder annotations in child/parent class请使用lombok版本:1.18.2,子/父类中的@SuperBuilder注解

If your parent class already has @Builder , then your child should be marked with @SuperBuilder .如果你的父类已经有@Builder ,那么你的孩子应该用@SuperBuilder标记。

Having both parent and child as @Builder won't work.将父母和孩子都作为@Builder行不通的。

Parent class A:父类A:

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

Child class B:儿童班B:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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