EnumValue.java // 自定义注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
// 用来验证String类型参数
String[] stringValue() default {};
// 用来验证Int类型参数
int[] intValue() default {};
@Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Documented
@interface List {
EnumValue[] value();
}
}
EnumValueValidator.java // 自定义注解实现
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
private String[] strValues;
private int[] intValues;
@Override
public void initialize(EnumValue constraintAnnotation) {
strValues = constraintAnnotation.stringValue();
intValues = constraintAnnotation.intValue();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) return true;
if (!(value instanceof String) && !(value instanceof Integer)) return true;
if (strValues != null && strValues.length > 0 && value instanceof String) {
return Arrays.asList(strValues).contains(value);
}
if (intValues != null && intValues.length > 0 && value instanceof Integer) {
return Arrays.stream(intValues).anyMatch(v -> v == (int) value);
}
return false;
}
}
用法:
@EnumValue(stringValue = {"yourValue"})
private String type;