I want to use Custom setter and constructor with static helper in Lombok:
@SuperBuilder(toBuilder = true)
public class Teacher extends User {
}
@Data
@SuperBuilder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(NON_NULL)
public class User implements Employee {
private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
private String username;
private String password;
User(String username, String password) {
System.out.println("*** test ***");
}
}
but when I create a Teacher object it seems that the constructor is not called because I don't see the test message in the console
Teacher.builder()
.username("username").password("pwd").build();
The point of the Builder pattern is almost always to return an immutable object from a builder object that is inherently mutable. The static helper you're referring to is the Builder pattern factory method used to create the User object. You shouldn't need to create a setter for User, instead User should be not defined with @Data.
If you need to call some method after construct of the User or Employee object just add a function to the respective class and call it after construct. Hiding work inside of a constructor other than initializing class members can be dangerous because you're hiding functionality and if it's a private method that functionality cannot be overridden.
@SuperBuilder(toBuilder = true)
public static class Teacher extends User {
}
@AllArgsConstructor
@SuperBuilder(toBuilder = true)
public static class User implements Employee {
private final String username;
private final String password;
}
public static void main(String[] args) {
Teacher teacher = Teacher.builder()
.username("username").password("pwd").build();
System.out.println(teacher.toString());
}
interface Employee {
}
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.