Java – used to check Lombok builders that are not null but not empty
•
Java
I have a variable class and I don't want it to be null or empty Is there any way to use the Lombok builder to set properties? I can use @ nonnull, but I cannot verify that it is empty Obviously, another option is to write my own builder to perform 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 } } }
Solution
Maxim kirilov's answer is incomplete It does not check for spaces / empty strings
I've encountered the same problem before, and I realized that in addition to using @ nonnull and @ builder from Lombok, I also overloaded the constructor with a private access modifier, where you can perform validation 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; }
In addition, it makes more sense to throw illegalargumentexception (rather than NPE) when string has null value, null value or null value
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码