I have a parent abstract class "Parent" and child class "Child". I am using @SuperBuilder to generate builder APIs. Now, I want to perform some validations on the members of class "Parent" and "Child" as part of build. I couldn't find any solution to customize lombok super builder. As per lombok doc, it seems to be possible. Can someone please shed some light?
@SuperBuilder
public abstract class Parent {
int x;
int y;
int z;
int a;
}
@SuperBuilder
public abstract class Child extends Parent {
int b;
int c;
int d;
// I want something like
public static class ChildBuilder {
public Child build() {
Child child = // Get child somehow;
validate(child);
}
}
}
The generated code for @SuperBuilder
is complex and loaded with type parameters. Therefore, it is advisable to delombok
your class and use the output as a reference.
You can do this with this command:
java -jar path/to/lombok.jar delombok -p path/to/src/main/java/Child.java
The output will show what code lombok generates. I assume the Child
class is not abstract (I think you have a typo in your questions). You want to customize the build()
method, so you are interested in the ChildBuilderImpl
, because this class contains that method. You can copy the class header to your source file and add your custom build()
method:
private static final class ChildBuilderImpl extends Child.ChildBuilder<Child, Child.ChildBuilderImpl> {
@java.lang.Override
public Child build() {
// Do validation here, e.g.:
if (((Child.ChildBuilder<?, ?>)this).b == 0)
throw new IllegalArgumentException("b must not be 0");
return new Child(this);
}
}
Remark: I would prefer performing the validation in the constructor, because otherwise you could programmatically invoke the constructor without the values getting validated. However, customizing the @SuperBuilder
constructor is not possible at the moment; it will be possible with the next lombok release. I'll update this question when it is released.
Update: You can customize the constructor since Lombok v1.18.16.
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