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;
//..
}
Since you are using the Hibernate Validator you can create your custom implementation of a
ConstraintValidatorinterface for your type:and then add a FQCN of this validator to
META-INF/services/jakarta.validation.ConstraintValidatorfileThis will solve the part of actually applying the constraint to your class. As for the
hibernate-validator-annotation-processorprocessor ... 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.