实施 Java 注释以进行验证
Implement Java annotations for validation
我想从 org.hibernate.validator.internal.constraintvalidators.
手动调用一个值的验证器,因为我无法注释 class。我所做的是这样的:
LengthValidator validator = new LengthValidator();
validator.initialize(new Length() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public Class<? extends Payload>[] payload() {
return null;
}
@Override
public int min() {
return min == null ? defaultMin : min;
}
@Override
public String message() {
return null;
}
@Override
public int max() {
return max == null ? defaultMax : max;
}
@Override
public Class<?>[] groups() {
return null;
}
});
Boolean valid = validator.isValid(myValue.asText(), null));
但是 Sonar 并不开心:
Lambdas and anonymous classes should not have too many lines
所以我尝试通过在自定义 class 中实现 @Length 来重构此代码,如下所示:
public class StringLength implements Length {
// All the methods overriden from @Length
}
但编译器抱怨
The annotation type Length should not be used as a superinterface for
StringLength
我怎样才能实现我想做的事情?
请注意,不鼓励使用内部 classes,但如果您真的想要,可以使用 Hibernate Validator AnnotationFactory
:
AnnotationDescriptor<Length> descriptor = new AnnotationDescriptor<Length>( Length.class );
descriptor.setValue( "min", 0 );
descriptor.setValue( "max", 10 );
...
Length lengthAnnotation = AnnotationFactory.create( descriptor );
虽然我不太确定,您使用 LengthValidator
会得到什么。您仍然无法使用 Validator 框架,对吗?如果不能注解class,能不能不用XML配置代替?
我想从 org.hibernate.validator.internal.constraintvalidators.
手动调用一个值的验证器,因为我无法注释 class。我所做的是这样的:
LengthValidator validator = new LengthValidator();
validator.initialize(new Length() {
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public Class<? extends Payload>[] payload() {
return null;
}
@Override
public int min() {
return min == null ? defaultMin : min;
}
@Override
public String message() {
return null;
}
@Override
public int max() {
return max == null ? defaultMax : max;
}
@Override
public Class<?>[] groups() {
return null;
}
});
Boolean valid = validator.isValid(myValue.asText(), null));
但是 Sonar 并不开心:
Lambdas and anonymous classes should not have too many lines
所以我尝试通过在自定义 class 中实现 @Length 来重构此代码,如下所示:
public class StringLength implements Length {
// All the methods overriden from @Length
}
但编译器抱怨
The annotation type Length should not be used as a superinterface for StringLength
我怎样才能实现我想做的事情?
请注意,不鼓励使用内部 classes,但如果您真的想要,可以使用 Hibernate Validator AnnotationFactory
:
AnnotationDescriptor<Length> descriptor = new AnnotationDescriptor<Length>( Length.class );
descriptor.setValue( "min", 0 );
descriptor.setValue( "max", 10 );
...
Length lengthAnnotation = AnnotationFactory.create( descriptor );
虽然我不太确定,您使用 LengthValidator
会得到什么。您仍然无法使用 Validator 框架,对吗?如果不能注解class,能不能不用XML配置代替?