有没有办法在另一个类的hibernate验证器中获取声明的约束值?

时间:2015-02-15 06:44:08

标签: java reflection hibernate-validator

使用hibernate验证器我声明类似这样的东西

public class TestSomething{

    @Length(max=30, message="Error Message.")
    private String name;

    getter and setter here
 }

在这种情况下是否可以获得最大字符数30

之类的东西
   TestSomething ts = new TestSomething();
   int maxValue =  ts.getName.getThatMaximumNumberOrSomethng

将java反思这种情况吗?

1 个答案:

答案 0 :(得分:1)

您应该使用Bean Validation元数据API。如果您有Validator个实例,则可以获得所谓的ConstraintDescriptor

BeanDescriptor beanDescriptor = getBeanDescriptor( TestSomething.class );
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty( "name" );
Set<ConstraintDescriptor<?>> constraintDescriptors = propertyDescriptor.getConstraintDescriptors();

一旦你有了ConstraintDescriptor的权利,你就可以打电话

constraintDescriptor.getAnnotation(); // to get the actual constraint annotation
constraintDescriptor.getAttributes().get("max"); // to retrieve the attribute from the attributes map provided by the descriptor as convenience