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.
The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.
Martin Grajcar. Your @Builder needs an @AllArgsConstructor (add it; feel free to make it private).
Especially knowing that “SuperBuilder” is still considered as an experimental feature.
In this tutorial we will see examples on how to apply this annotation at class level, constructor level and method level. Builder pattern is a commonly used creational design pattern in application development which solves the instance creation problems with Factory and Abstract Factory design patterns.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With