简体   繁体   中英

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.

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 delombok ed 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM