javax.validation 自定义注解统一校验枚举类型

1.自定义接口 

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValidator.class})
public @interface EnumValid {
String message() default "数据校验不通过";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};

int[] values() default {};

/**
* 目标枚举类
*/
Class<?> target() default Object.class;

/**
* 是否忽略空值
*/
boolean ignoreEmpty() default true;
}

2.校验枚举 

public class EnumValidator implements ConstraintValidator<EnumValid, Object> {
    // 枚举校验注解
    private EnumValid annotation;

    @Override
    public void initialize(EnumValid constraintAnnotation) {
        annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value,
 ConstraintValidatorContext constraintValidatorContext) {
        boolean result = false;

        Class<?> cls = annotation.target();
        boolean ignoreEmpty = annotation.ignoreEmpty();

        // target为枚举,并且value有值,或者不忽视空值,才进行校验
        if (cls.isEnum() && ((value != null 
     && StrUtil.isNotBlank(value.toString())) || !ignoreEmpty)) {
            String simpleName = cls.getSimpleName();
            try {
                //反射获取枚举类
                Class<Enum> clazz = (Class<Enum>) Class.forName("xx.xx.xx." + simpleName);
                //获取所有枚举实例
                Enum[] enumConstants = clazz.getEnumConstants();
                //根据方法名获取方法
                Method getValue = clazz.getMethod("getValue");
                for (Enum enum1 : enumConstants) {
                    //执行枚举方法获得枚举实例对应的值
                    Object invoke = getValue.invoke(enum1);
                    if (invoke.toString().equals(String.valueOf(value))) {
                        result = true;
                        break;
                    }
                }
            } catch (Exception e) {
                LogUtils.error(e);
                return true;
            }
        }else if (annotation.values().length > 0 && (value != null || !ignoreEmpty)){
            for (int val : annotation.values()) {
                if (String.valueOf(val).equals(String.valueOf(value))){
                    result = true;
                    break;
                }
            }
        } else {
            result = true;
        }
        return result;
    }
}

3.定义枚举类

public enum CmsStatus {
    /**
     * Cms审核状态
     */
    CHECKED(1, "置顶"),
    CHECKING(2, "推荐"),
    DRAFT(3, "栏目"),
    BACK_DRAFT(4, "退稿"),
    ;
    private final Integer value;
    private final String message;

    public Integer getValue() {
        return value;
    }

    public String getMessage() {
        return message;
    }

    CmsStatus(Integer value, String message) {
        this.value = value;
        this.message = message;
    }
}

4.使用注解 (在需要检验的字段上使用注解)

@EnumValid(target = CmsStatus.class,message = "审核状态值有误")
private Integer status;

关于作者

不羁的风
一起哈皮YQHP
获得点赞
文章被阅读