Lombok Customize SuperBuilder

I recently tried customizing @SuperBuilder using Lombok 1.18.8 and IntelliJ, and it worked fine. The only issue I faced was, I lost ability to use toBuilder flag in SuperBuilder - @SuperBuilder(toBuilder=true).

Below is the code to override @SuperBuilder methods.

public static abstract class ChildBuilder<C extends Child, B extends ChildBuilder<C, B>>
        extends ParentBuilder<C, B> {

    private LocalDate date;

    public B date(String dateStr) {
        this.date = LocalDate.parse(dateStr);
        return self();
    }
}

I added my working code here: Customize SuperBuilder in Lombok


When @SuperBuilder was introduced in 1.18.2, customising it was not possible. If you try, Lombok 1.18.2 gives you the error message SuperBuilder does not support customized builders.

However, Lombok 1.18.4 added limited customisation possibilities of @SuperBuilder. (It's limited because you cannot modify setter methods, but you can add your own methods and modify build() and builder().)

The generated @SuperBuilder code is quite complex and differs from @Builder. To avoid accidently messing up the generics-loaded builder code, you should start by copying the builder class header from the delombok output. In your case (adding a new setter method), customize the abstract builder class ParentBuilder (and not the ParentBuilderImpl). Have a look at the delomboked code to find out how your setter should be defined, especially the return type.

This is the customized builder code for your example:

public abstract static class ParentBuilder<C extends Parent, B extends ParentBuilder<C, B>> {
    public B setAllTo(final int value) {
       return a(value).b(value);
    }
}

With Lombok 1.18.4, this compiles and works as expected.

Tags:

Java

Lombok