使用 hibernate validator 我声明了这样的东西
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会不会对这种情况进行反射(reflection)?
最佳答案
您应该使用 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
关于java - 有没有办法在另一个类的 hibernate validator 中获取约束的声明值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28523703/