使用 ConstraintValidator 实现接口枚举校验
自定义一个注解类
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {EnumValidator.class})
@Documented
public @interface EnumValid {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<?> target() default Class.class;
boolean ignoreEmpty() default true;
}
实现方法
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumValid, Object> {
private final static String METHOD_NAME = "getValue";
private EnumValid annotation;
@Override
public void initialize(EnumValid constraintAnnotation) {
annotation = constraintAnnotation;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
Class<?> cls = annotation.target();
boolean ignoreEmpty = annotation.ignoreEmpty();
if (cls.isEnum() && !ignoreEmpty) {
return true;
}
boolean isCheck = cls.isEnum() && null != value;
if (!isCheck) {
return false;
}
boolean result = false;
Object[] objects = cls.getEnumConstants();
try {
Method method = cls.getMethod(METHOD_NAME);
for (Object obj : objects) {
Object code = method.invoke(obj);
if (Objects.deepEquals(value, code)) {
result = true;
break;
}
}
} catch (Exception e) {
log.error("EnumValidator call isValid() method exception", e);
}
return result;
}
}
使用注解
@EnumValid(message = "状态不对", target = StatusEnum.class, ignoreEmpty = false)
private Integer status;
注意实项
1.枚举需要有 value属性,因为验证是通过反射获取getValue() 方法去获取值,然后对比