枚举类型参数验证

EnumValid.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Documented
@Constraint(validatedBy = EnumValidator.class)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface EnumValid {

Class<? extends Enum<?>> enumClass();

String message() default "invalid enum item value.";

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

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

校验器EnumValidator.java

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
32
33
34
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumValid, String> {

private Class<? extends Enum<?>> enumClass;

@Override
public void initialize(EnumValid enumValid) {
enumClass = enumValid.enumClass();
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (!valid(value)) {
throw new RuntimeException("invalid input parameter.");
return false;
}
return true;
}

private boolean valid(String value) {
try {
if (enumClass.isEnum()) {

Method method = enumClass.getMethod("isValidName", value.getClass());
Boolean result = (Boolean)method.invoke(null, value);
return result != null && result;
}
} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException("Enum values valid error.");
}
return false;
}

}

枚举类

1
2
3
4
5
6
7
8
9
public enum SxWhetherIntEnum  {
YES,
NO;

public static boolean isValidName(String name) {
return Arrays.stream(values()).anyMatch(item -> item.name().equals(name));
}

}

使用的时候,注解作用在DTO字段上:

1
2
3
4
5
6
public class RequestDto {

@ApiModelProperty(value = "是否可转定,1-是,2-否(补充)")
@EnumValid(enumClass = SxWhetherIntEnum.class)
private Integer payable;
}

参考文章

评论