Home > Software engineering >  Get the Javax Validation Annotation Attribute Value
Get the Javax Validation Annotation Attribute Value

Time:06-15

I have set of properties with typical Java validation annotations (Hibernate implementation), e.g.,

@Size(max = 10)
private String data;

I would like to know if programmatically the Size's max value can be accessed.

This is needed to perform some transformative operation on data when it's retrieved. Obviously, 10 can be hard coded to a final static class variable, but is there a way to access these annotation values?

CodePudding user response:

Since the annotation has a runtime retention, you can access it through reflection. For instance (ignoring any exceptions):

Field field = MyClass.class.getDeclaredField("data");
Size size = field.getAnnotation(Field.class);
int max = size.max();

If you want to get the value that triggered a constraint error, catch the ConstraintViolationException. You can then get the constraint annotation from the violation. Another example:

// just some code to get a descriptor
ConstraintDescriptor<?> descriptor = constraintViolationException.getAnnotations().stream()
        .map(ConstraintViolation::getConstraintDescriptor)
        .findAny()
        .orElseThrow();

// now its properties can be accessed
Map<String, Object> attributes = descriptor.getAttributes();
// attributes contains an entry with key "max" and value 10 for your @Size annotation
Size size = (Size) descriptor.getAnnotation();
int max = size.max();
  • Related