龙目岛建造者检查非空和不空

2022-09-01 14:19:01

我有一个带有变量的类,我不希望它是空的或空的。有没有办法使用龙目岛生成器来设置属性?我可以使用,但我无法验证它是否为空。显然,另一种选择是编写我自己的构建器来执行所有这些检查。例如:@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
        }
    }
}

答案 1

马克西姆·基里洛夫的回答是不完整的。它不会检查空白/空字符串。

我以前遇到过同样的问题,我意识到除了使用龙目岛@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;
}

此外,当字符串具有空白,空或空值时,抛出非法参数异常更有意义(而不是NPE)。


答案 2

构建器注释应该可以解决您的问题:

@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 验证将在对象构造期间进行。


推荐