Reputation: 143
I have read this this post about using lombok @Bulider
with inheritance https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/
All works good. But in my case I need also use builder for Parent class
, and this workaround doesn`t work.
I tried add @Builder
to Parent class
also but got Compilation failure because Child class
try to override builder()
method from Parent.
@AllArgsConstructor
public class Parent {
private final long a;
private final long b;
private final double c;
}
public class Child extends Parent{
private final long aa;
private final long bb;
private final double cc;
@Builder
public Child(long a, long b, long c,
long aa, long bb, long cc)
super(a,b,c);
this.aa = aa;
this.bb = bb;
this.cc =cc;
}
I need both case builder like:
Parent.builder().a(10).b(20).build();
Child.builder().a(10).aa(20).bb(100).build();
Does lombok can handle that case?
Upvotes: 2
Views: 3948
Reputation: 5808
Lombok has introduced experimental features with version: 1.18.2 for inheritance issues faced with Builder annotation, and can be resolved with @SuperBuilder annotation as below.
@SuperBuilder
public class ParentClass {
private final String a;
private final String b;
}
@SuperBuilder
public class ChildClass extends ParentClass{
private final String c;
}
Now, one can use Builder class as below (that was not possible with @Builder annotation)
ChildClass.builder().a("testA").b("testB").c("testC").build();
Upvotes: 4
Reputation: 143
Lombok try to override builder()
method from Parent class in Child.
So I tried to set not default name to builder method.
@Builder(builderMethodName = "parentBuilder")
@AllArgsConstructor
public class Parent {
private final long a;
private final long b;
private final double c;
}
public class Child extends Parent{
private final long aa;
private final long bb;
private final double cc;
@Builder(builderMethodName = "childBuilder")
public Child(long a, long b, long c,
long aa, long bb, long cc)
super(a,b,c);
this.aa = aa;
this.bb = bb;
this.cc =cc;
}
That works for me.
Upvotes: 6