java 龙目岛建设者的继承
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37751900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inheritance for builders in lombok
提问by Abhinav Aggarwal
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? I do not want to write the complete builder for for B, unless I don't have any other option.
有没有办法使用 lombok 来做到这一点?我不想为 B 编写完整的构建器,除非我别无选择。
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.
PS:由于问题,我已经为 B 类提供了显式构造函数。我尝试搜索,但找不到相同的好的解决方案。
回答by Abhinav Aggarwal
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();
}
}
}
回答by Amit Kaneria
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注解
回答by realPK
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. If you have multiple level of inheritance, please avoid Lombok or it will make your Java models messy.
一个旁注,@SuperBuilder 注释在撰写此答案时在 IntelliJ 中不起作用。如果您有多层继承,请避免使用 Lombok,否则它会使您的 Java 模型变得混乱。