Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the Javax Validation Annotation Attribute Value

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading