我有一个带变量的类我不希望它为null或为空。有没有办法使用Lombok构建器来设置属性?我可以使用@NonNull
,但我无法验证它是否为空。显然,另一种选择是编写我自己的构建器来执行所有这些检查。例如:
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
}
}
}
答案 0 :(得分:12)
Maxim Kirilov的回答是不完整的。它不会检查空格/空字符串。
之前我遇到过同样的问题,我意识到除了使用来自Lombok的@NonNull和@Builder之外,还使用私有访问修饰符重载构造函数,您可以在其中执行验证。像这样:
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;
}
此外,当String具有空白,空值或空值时,抛出IllegalArgumentException会更有意义(而不是NPE)。
答案 1 :(得分:7)
构建器注释应解决您的问题:
@Builder
class Person {
@NonNull
private String firstName;
@NonNull
private String lastName;
}
生成的代码是:
class Person {
@NonNull
private String firstName;
@NonNull
private String lastName;
@ConstructorProperties({"firstName", "lastName"})
Person(@NonNull String firstName, @NonNull String lastName) {
if(firstName == null) {
throw new NullPointerException("firstName");
} else if(lastName == null) {
throw new NullPointerException("lastName");
} else {
this.firstName = firstName;
this.lastName = lastName;
}
}
public static Person.PersonBuilder builder() {
return new Person.PersonBuilder();
}
public static class PersonBuilder {
private String firstName;
private String lastName;
PersonBuilder() {
}
public Person.PersonBuilder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public Person.PersonBuilder lastName(String lastName) {
this.lastName = lastName;
return this;
}
public Person build() {
return new Person(this.firstName, this.lastName);
}
public String toString() {
return "Person.PersonBuilder(firstName=" + this.firstName + ", lastName=" + this.lastName + ")";
}
}
}
在这种情况下,将在对象构造期间进行空验证。
答案 2 :(得分:1)
我做了类似的事,
class Person {
private String mFristName;
private String mSecondName;
@Builder
Person(String firstName, String secondName) {
mFristName = PreCondition.checkNotNullOrEmpty(firstName);
mSecondName = PreCondition.checkNotNullOrEmpty(secondName);
}
}
class PreCondition {
static <T> T checkNotNullOrEmpty(T instance) {
if (instance == null || (instance instanceof String && ((String) instance).isEmpty())) {
throw new NullOrEmptyException();
}
return instance;
}
static class NullOrEmptyException extends RuntimeException {
NullOrEmptyException() {
super("Null or Empty");
}
}
}
答案 3 :(得分:0)
您是否尝试过“ @NotEmpty”?它在javax.validation.constraints包中
https://javaee.github.io/javaee-spec/javadocs/javax/validation/constraints/NotEmpty.html