I use Project Lombok for generate the getter/setter for String field. This field, for example password, has validation annotation.
@Size(min = 6,max = 100, message = "The password must be between 6 and 100 characters")
private String password;
I wanna add trim method in the setter for not counting white space in the length.
public void setPassword(String password) {
this.password = password.trim();
}
How can I add trim method in Lombok setter? Or I must write custom setter?
In this case you would have to write a custom setter. If you were using the Immutable equivalent (Wither), you could put the trim() inside the constructor and just add @Wither to the method, and this would also hold for builders generated via @Builder also. It's a safer approach, that ensures the password will always be trimmed.
@Wither
@Size(min = 6,max = 100, message = "The password must be between 6 and 100 characters")
private final String password; //guaranteed to be trimmed
public MyClass(final String password){
this.password= password.trim();
}
Update:
@Wither was introduced as experimental feature in lombok v0.11.4. @Wither was renamed to @With, and moved out of experimental and into the core package, in lombok v1.18.10.
From the aboce link to Wither.