1

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 ?

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

In fact, I want to validate schemaless data and I don't want to rewrite validators that work perfectly in Hibernate. So I can't use XML configuration since I don't know the structure of the data to validate. That's why I want to build annotations and call validators "dynamically". I'm going to try AnnotationDescriptor ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.