Currently I have these three classes:
@Value
@NonFinal
@SuperBuilder
public class Parent {
// Some fields
}
@Value
@EqualsAndHashCode(callSuper = true)
@SuperBuilder(toBuilder = true)
public class ChildA extends Parent {
// Some fields
}
@Value
@EqualsAndHashCode(callSuper = true)
@SuperBuilder(toBuilder = true)
public class ChildB extends Parent {
// Some fields
}
I want to use it in a mapper as follows to avoid duplicating any code:
private ChildA buildChildA(Entity entity) {
Parent parent = ((ChildB) buildParent(entity, ChildA.builder().build()))
.toBuilder()
// Populate Child A fields from entity
.build();
}
private ChildB buildChildB(Entity entity) {
Parent parent = ((ChildA) buildParent(entity, ChildA.builder().build()))
.toBuilder()
// Populate Child B fields from entity
.build();
}
private Parent buildParent(Partner entity, Parent parent) {
return parent.toBuilder()
// Populate Parent fields here
.build();
}
However when I try to compile I get:
ChildA.java:13: error: method does not override or implement a method from a supertype
@SuperBuilder(toBuilder = true)
^
ChildB.java:13: error: method does not override or implement a method from a supertype
@SuperBuilder(toBuilder = true)
^
2 errors
How do you use toBuilder with @SuperBuilder? I'm using lombok v1.18.4.
Install the Builder Theme on your Super site Click on the Theme you have selected to use. You'll see a box with the 'code' you need to copy and install on your Super site. Go to super.so and open the site where you are adding the theme. In the Builder template on your notion site, select and copy the code snippet.
The @Builder annotation produces complex builder APIs for your classes. @Builder lets you automatically produce the code required to have your class be instantiable with code such as: Person. builder()
toBuilder=true means that we additionally created a toBuilder() instance method that creates a new instance of the builder class, initialized with the values from the current instance. We added a toString() method with a @ToString annotation. We added hashCode() and equals() with, you guessed it, @EqualsAndHashCode.
Project Lombok's @Builder is a helpful mechanism for using the Builder pattern without writing boilerplate code. We can apply this annotation to a Class or a method. In this quick tutorial, we'll look at the different use cases for @Builder.
If you want to use @SuperBuilder
with toBuilder
, all classes in the hierarchy must have toBuilder=true
. The reason is that the toBuilder()
method only copies the field values from its respective class, but delegates the copying of the field values from the supertypes to the supertypes' toBuilder()
methods.
So just add toBuilder=true
to your Parent
class, too.
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