Implement Java annotations for validation
I want to call a Validator from org.hibernate.validator.internal.constraintvalidators.
manually on a value because I can't annotate the class. What I've done is this :
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));
But Sonar is not happy :
Lambdas and anonymous classes should not have too many lines
So I tried to refactor this code by implementing @Length in a custom class like this :
public class StringLength implements Length {
// All the methods overriden from @Length
}
but the compiler complains
The annotation type Length should not be used as a superinterface for StringLength
How can I achieve what I want to do ?
Note that the use of internal classes is not encouraged, but if you really wanted to, you could use the Hibernate Validator AnnotationFactory
:
AnnotationDescriptor<Length> descriptor = new AnnotationDescriptor<Length>( Length.class );
descriptor.setValue( "min", 0 );
descriptor.setValue( "max", 10 );
...
Length lengthAnnotation = AnnotationFactory.create( descriptor );
I am not quite sure though, what you gain using LengthValidator
. You still cannot make use of the Validator framework, right? If you cannot annotate the class, can you not use XML configuration instead?
下一篇: 实现用于验证的Java注释