我有一个表单 bean(Employee),可以在不同的屏幕上共享。为了区分不同屏幕上的字段,我计划使用带有组名称的 JSR 自定义注释对字段进行分组。
例如,
class Employee {
@Screen(groups={EmployeeScreen.class})
private employeeNo;
@Screen(groups={EmployeeScreen.class})
private employeeName;
@Screen(groups={RoleScreen.class})
private roleName;
我如何读取与组名称(EmployeeScreen 和 RoleScreen)关联的 bean 的所有属性名称。任何帮助将非常感激。谢谢。
最佳答案
Bean Validation 提供元数据 API,因此只要您有权访问 Validator
实例,您就可以执行以下操作:
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
}
这是否对您有帮助取决于上下文。您是否使用 Bean Validation 作为其他框架的一部分?
关于java - 如何使用 JSR 注释组从 bean 获取属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088328/