我目前正在做一个辅助项目,以使用Java 8验证对象。
目前我有这个:
- 本质上是对Java 8谓词接口的重写的接口:
然后,我创建了相同接口的实现:
然后这个类是我验证的结果
具体的对象验证可以在这里找到:
public class ConcreteValidator implements EmployeeValidator {
@Override
public void validate(Employee employee) throws EmployeeException {
ValidatorUtil.notNullString.and(ValidatorUtil.notEmptyString)
.and(ValidatorUtil.stringBetween(1,100)).test(employee.getFirstName())
.getFieldNameIfInvalid(" Please specify valid firstname ").orElse("");
ValidatorUtil.notNullString.and(ValidatorUtil.notEmptyString)
.and(ValidatorUtil.stringBetween(1,100)).test(employee.getLastName())
.getFieldNameIfInvalid(" Please specify valid lastname ").orElse("");
ValidatorUtil.notNullString.and(ValidatorUtil.notEmptyString)
.and(ValidatorUtil.stringBetween(3,100)).test(employee.getEmail())
.getFieldNameIfInvalid(" Please specify valid email ").orElse("");
ValidatorUtil.notNullInteger.and(ValidatorUtil.greaterThanZero)
.and(ValidatorUtil.integerBetween(18,60)).test(employee.getage())
.getFieldNameIfInvalid(" Please specify valid age ").orElse("");
}
}
这很好用,但是我现在要做的是限制用户首先使用notNull验证,只有在验证之后,诸如notEmpty或GreaterThanZero之类的所有方法才可用。
我搜索了流畅的界面,但不知道这是否是正确的方法(想做这样的事情:https://code-held.com/2019/04/29/robust-builder-pattern/)
总而言之,我想强迫开发人员先验证对象是否为null,然后再验证所有其他方法,例如java-8中Stream API的链接。这是我的customValidations。