Sandro Rey
Sandro Rey

Reputation: 2989

Use custom setter in Lombok's builder with superclass

I want to use custom setter in Lombok's builder and overwrite 1 method, like this

@SuperBuilder
public class User implements Employee {
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private String username;

    private String password;

    public static class UserBuilder {
        public UserBuilder password(String password) {
            this.password = ENCODER.encode(password);
            return this;
        }
    }
}

but I have this compilation error

Existing Builder must be an abstract static inner class.

Upvotes: 6

Views: 2975

Answers (1)

Jan Rieke
Jan Rieke

Reputation: 8052

In contrast to @Builder, @SuperBuilder generates two builder classes, a public and a private one. Both are heavily loaded with generics to ensure correct type inference.

If you want to add or modify a method to the builder class, you should have a look at the uncustomized delomboked code and copy&paste the public abstract static class header from there. Otherwise you'll likely get the generics wrong, leading to compiler errors you won't be able to fix. Also have a look at the return types and statements of the generated methods to make sure you define that correctly.

The @SuperBuilder documentation also mentions this:

Due to the heavy generics usage, we strongly advice to copy the builder class definition header from the uncustomized delomboked code.

In your case, you have to customize the builder as follows:

public static abstract class UserBuilder<C extends User, B extends User.UserBuilder<C, B>> {
    public B password(final int password) {
        this.password = ENCODER.encode(password);
        return self();
    }
}

Upvotes: 5

Related Questions