枚举校验

注解

1
2
3
4
5
6
7
8
9
10
11
12
13
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValidator.class})
public @interface Enum {
Class<?> target() default Class.class;

String field() default "code";

boolean notEmpty() default false;

String message() default "";
}

处理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class EnumValidator implements ConstraintValidator<Enum, String> {
private Enum annotation;

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

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
boolean res = false;
Class<?> clazz = annotation.target();
if (clazz.isEnum() && (!value.isEmpty() || !annotation.notEmpty())) {
Object[] objs = clazz.getEnumConstants();
Field field;
try {
field = clazz.getField(annotation.field());
ReflectionUtils.makeAccessible(field);
for (Object obj : objs) {
if (field.get(obj).toString().equals(value)) {
res = true;
break;
}
}
} catch (NoSuchFieldException | IllegalAccessException ignore) {
// 异常
}
}
return res;
}
}