A:对实体的校验:
User user = new User(); user.setPwd("1223eeee"); user.setName("1"); // 需要校验的方法实例 ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Set<ConstraintViolation<User>> constraintViolationSet = factory.getValidator().validate(user); System.out.println("非法参数校验结果条数: " + constraintViolationSet.size()); for(ConstraintViolation<User> item:constraintViolationSet){ System.out.println("-----xx-:"+item.getMessage() ); }
B:对 类中 方法的校验:
// 需要校验的方法实例
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
ExecutableValidator validator = factory.getValidator().forExecutables();
Method method = this.getClass().getMethod("vaildMethod", Integer.class, String.class, String.class);
// 校验参数,应该是有两个非法的参数
Object [] params = new Object[]{100, "", "test"};
// 获得校验结果 Set 集合,有多少个字段校验错误 Set 的大小就是多少 Set<ConstraintViolation<ExecutableValidatorTest>> constraintViolationSet = validator.validateParameters(this, method, params);
System.out.println("非法参数校验结果条数: " + constraintViolationSet.size()); constraintViolationSet.forEach(cons -> {
System.out.println("非法消息: " + cons.getMessage());
});
params = new Object[]{10, "build-test", "test"};
constraintViolationSet = validator.validateParameters(this, method, params);
System.out.println("合法参数校验结果条数: " + constraintViolationSet.size());