构建器注释应该可以解决您的问题:
@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 + ")";
}
}
}
在这种情况下,null 验证将在对象构造期间进行。