美文网首页
JSR303校验工具类

JSR303校验工具类

作者: ouyangan | 来源:发表于2020-03-08 18:55 被阅读0次
    public enum ValidatorUtil {
        instance;
        public static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    
        public void valid(Object o, Class group) throws IllegalArgumentException {
            Set<ConstraintViolation<Object>> validate = validator.validate(o, group);
            if (validate.size() > 0) {
                String msg = msgPrettyFormat(validate);
                throw new IllegalArgumentException(msg);
            }
        }
    
        public void valid(Object o) throws IllegalArgumentException {
            Set<ConstraintViolation<Object>> validate = validator.validate(o);
            if (validate.size() > 0) {
                String msg = msgPrettyFormat(validate);
                throw new IllegalArgumentException(msg);
            }
        }
    
        private String msgPrettyFormat(Set<ConstraintViolation<Object>> validate) {
            StringBuilder stringBuilder = new StringBuilder();
            for (ConstraintViolation<Object> constraintViolation : validate) {
                stringBuilder
                        .append("[")
                        .append(constraintViolation.getPropertyPath())
                        .append("=")
                        .append(constraintViolation.getInvalidValue())
                        .append(" -> ")
                        .append(constraintViolation.getMessage())
                        .append("] ");
            }
            return stringBuilder.toString();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:JSR303校验工具类

          本文链接:https://www.haomeiwen.com/subject/qxsjdhtx.html