Lombok builder to check non null and not empty

user1692342 :

I have a class with variables I don't want it to be null or empty. Is there a way to use Lombok builder to set the property? I can use @NonNull but I won't be able to verify if it is empty or not. Obviously the other option is to write my own builder which does all these checks. For example:

class Person {
    @NonNull
    private String firstName;
    @NonNull
    private String lastName;

    public static class PersonBuilder() {
        // .
        // .
        // .
        public Person build() {
            //do checks for empty etc and return object
        }
    }
}
Kedar Prabhu :

Maxim Kirilov's answer is incomplete. It doesn't check for blank/empty Strings.

I've faced the same issue before, and I realized that in addition to using @NonNull and @Builder from Lombok, overload the constructor with a private access modifier, where you can perform the validations. Something like this:

private Person(final String firstName, final String lastName) {
    if(StringUtils.isBlank(firstName)) {
        throw new IllegalArgumentException("First name can't be blank/empty/null"); 
    }
    if(StringUtils.isBlank(lastName)) {
        throw new IllegalArgumentException("Last name can't be blank/empty/null"); 
    }
    this.firstName = firstName;
    this.lastName = lastName;
}

Also, throwing IllegalArgumentException makes more sense (instead of NPE) when String has blank, empty or null values.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430063&siteId=1