对您的问题的简短回答:不,您不能只添加一个额外的字段,也不能使用继承来添加额外的字段。请参阅this question,它解释了为什么 Java 不允许使用注释进行继承。
您需要做的是创建您自己的特定版本的@Size 注释。但是您应该能够将 @Size 注释应用于您的自定义注释,以便在您运行验证时自动检查 @Size。
您的注释可能看起来像这样:
@Constraint(validatedBy = { })
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
//The only downside of this approach
//is that you have to hardcode your min and max values
@Size(min=5, max=10)
public @interface CodedSize {
String message() default "{Default Validation Message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
int code() default 0;
}
如果您还想在注释中指定大小,您可以这样做,并编写一个自定义验证器来验证您的注释。
@Constraint(validatedBy = { CodedSizeValidator.class })
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CodedSize {
String message() default "{Default Validation Message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
int minSize() default 5;
int maxSize() default 10;
int code() default 0;
}
然后你的自定义验证器看起来像这样:
public class CodedSizeValidator implements ConstraintValidator<CodedSize, String> {
private int minSize;
private int maxSize;
private int code;
@Override
public void initialize(CodedSize constraintAnnotation){
this.minSize = constraintAnnotation.minSize();
this.maxSize = constraintAnnotation.maxSize();
this.code = constraintAnnotation.code();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
boolean isValid = false;
if(value == null || value.isEmpty()) {
//if a null or empty value is valid, then set it here.
isValid = true;
} else {
//Logic here to determine if your value is valid by size constraints.
}
return isValid;
}
}
我使用了String,因为这似乎是最适用的,但是您可以轻松地使用Number,甚至可以使用泛型类型来允许您在多个字段上使用此注释。这样做的好处是,如果您想在此验证中添加一个空签入,您可以这样做。
如果多次验证失败,ConstraintValidatorContext 可用于构建您的错误消息。您可以根据需要进行详细说明,但请注意,此代码可能会很快变成意大利面条。