您可以创建自己的接受多个值的注释。这涉及编写一个注解类和Validator类:
public class OneOfValidator implements ConstraintValidator<OneOf, Integer> {}
与注解:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = OneOfValidator.class)
public @interface OneOf {
String message() default "value must match one of the values in the list";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int[] value() default {};
}
然后,您可以使用它像:
@OneOf({2, 3, 5, 9})
复制了好听的名字'OneOf'从@Gunnar :) – john16384