0

I have a form bean (Employee) which can be shared across different screens. To differentiate the fields across screens used, i had planned group the fields using JSR custom annotation with a group name.

For example,

class Employee {

@Screen(groups={EmployeeScreen.class})
private employeeNo;

@Screen(groups={EmployeeScreen.class})
private employeeName;

@Screen(groups={RoleScreen.class})
private roleName;

How could i read all the attribute names of the bean associated to group names (EmployeeScreen and RoleScreen). Any help would be very much appreciated. Thanks.

Karthik
  • 522
  • 3
  • 13

1 Answers1

1

Bean Validation offers a metadata API, so provided you have access to the Validator instance, you can do something like:

BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Employee.class );

Set<PropertyDescriptor> propertyDescriptors = beanDescriptor.getConstrainedProperties();

for(PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    Set<ConstraintDescriptor<?>> descriptorsForGroup = propertyDescriptor.findConstraints()
                .unorderedAndMatchingGroups( EmployeeScreen.class )
                .getConstraintDescriptors();

     // if descriptorsForGroup is not empty you found a property which has a constraint matching the specified group
     // propertyDescriptor.getPropertyName() gets you the property name

}

Whether this is helpful for you, will depend on the context. Are you using Bean Validation as part of a other framework?

Hardy
  • 18,659
  • 3
  • 49
  • 65