Possible to use one of the existing standard Java constraint annotations (`@Size`) on my custom Java type?

51 views Asked by At

Is it possible to use one of the existing standard Java constraint annotations (@Size) on my new Java type (MyType)?

I don't want consumers of my framework to have to use non-standard annotations in order to apply a simple size constraint to the new data type.

I'd like to be able to apply @Size to fields of type MyType, but I get this error by hibernate-validator-annotation-processor:

SampleDTO.java:3: error: The annotation @Size is disallowed for this data type.
  @Size(max = 100)
  ^

Is there a way to get this to work?

So far I have a DTO class which contains 1 field of type MyType:

public class SampleDTO {

  @Size(max = 100)
  public MyType fileContent;
}

MyType basically contains a byte[] (which will correspond to file content):

public class MyType {

  private byte[] value;

  //..
}
1

There are 1 answers

4
mark_o On

Since you are using the Hibernate Validator you can create your custom implementation of a ConstraintValidator interface for your type:

public class MyClassSizeValidator implements ConstraintValidator<Size, MyType> {

    @Override
    public void initialize(Size constraintAnnotation) {
        // ....
    }

    public boolean isValid(MyType value, ConstraintValidatorContext context) {
        // ....
    }
}

and then add a FQCN of this validator to META-INF/services/jakarta.validation.ConstraintValidator file

com.acme.validation.validators.MyClassSizeValidator

This will solve the part of actually applying the constraint to your class. As for the hibernate-validator-annotation-processor processor ... it "doesn't know" about the constraints that aren't built-in so I'd suspect that it'll still complain about it. But you do not necessarily need the processor.