如何使用 JSR 注释组从 bean 获取属性?
How to get attributes from a bean using JSR annotation groups?
我有一个可以跨不同屏幕共享的表单 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 用作其他框架的一部分?
我有一个可以跨不同屏幕共享的表单 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 用作其他框架的一部分?