使用休眠验证器,我这样声明
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会思考这种情况吗?
最佳答案
您应该使用Bean验证元数据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