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

请大神们多多指点评论,不胜感激,有问题也可以评论提问

1.自定义接口 

@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {EnumValidtor.class})
@Documented
public @interface EnumValidAnnotation {
    String message() default "";

    Class[] groups() default {};

    Class[] payload() default {};

    Class[] target() default {};
}

2.校验枚举 

public class EnumValidtor implements ConstraintValidator {

    Class[] cls ; //枚举类

    @Override
    public void initialize(EnumValidAnnotation constraintAnnotation) {
        cls = constraintAnnotation.target();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(cls.length>0 ){
            for (Class cl : cls
                    ) {
                try {
                    if(cl.isEnum()){
                        //枚举类验证
                        Object[] objs = cl.getEnumConstants();
                        Method  method = cl.getMethod("name");
                        for (Object obj : objs
                                ) {
                            Object code = method.invoke(obj,null);
                            if(value.equals(code.toString())){
                                return true;
                            }
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        } else {  
                return true;   
        }  
         return false;
    }
}       

3.定义枚举类

public enum   ProductTypeEnum {
    P("原材料"), M("加工品");
}

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

@EnumValidAnnotation(message = "商品类型输入错误",target = ProductTypeEnum.class )

你可能感兴趣的:(validation 自定义注解统一校验枚举类型)