您可以創建自己的接受多個值的註釋。這涉及編寫一個註解類和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