使用版本 Hibernate Validator 4.3.0.Final。
当我拨打以下电话时:
Set<ConstraintViolation<T>> violations = validator.validateProperty(objectForValidation, "list[0].field1", groups);
在一个 ClassForValidation 实例上填充了一个带有 field1 = "" 的 ChildClassForValidation 实例
public class ClassForValidation {
@NotEmpty
private String fielda;
@Valid
private List<ChildClassForValidation> list = new ArrayList<ChildClassForValidation>();
public ClassForValidation(List<> list, String fielda) {
this.list = list;
this.fielda = fielda;
}
}
public class ChildClassForValidation {
@NotEmpty
private String field1;
public ChildClassForValidation(String field1) {
this.field1 = field1;
}
}
我得到以下异常:
java.lang.IllegalArgumentException: HV000039: Invalid property path. There is no property field1 in entity java.util.ArrayList.
at org.hibernate.validator.internal.engine.ValidatorImpl.collectMetaConstraintsForPath(ValidatorImpl.java:1141)
at org.hibernate.validator.internal.engine.ValidatorImpl.collectMetaConstraintsForPath(ValidatorImpl.java:1179)
at org.hibernate.validator.internal.engine.ValidatorImpl.validatePropertyInContext(ValidatorImpl.java:616)
at org.hibernate.validator.internal.engine.ValidatorImpl.validateProperty(ValidatorImpl.java:151)
...
在查看了 Hibernate Validator 源代码后,我得出的结论是这是一个错误。因为在源代码中似乎有代码试图同时处理列表和地图。我相信错误在于org.hibernate.validator.internal.engine.ValidatorImpl中的以下代码
private <T, U, V> ValueContext<U, V> collectMetaConstraintsForPath(Class<T> clazz, Object value, Iterator<Path.Node> propertyIter, PathImpl propertyPath, List<MetaConstraint<?>> metaConstraintsList) {
Path.Node elem = propertyIter.next();
Object newValue = value;
BeanMetaData<?> metaData = beanMetaDataManager.getBeanMetaData( clazz );
//use precomputed method list as ReflectionHelper#containsMember is slow
if ( !metaData.isPropertyPresent( elem.getName() ) ) {
throw log.getInvalidPropertyPathException( elem.getName(), metaData.getBeanClass().getName() );
}
...
}
在这段代码中,它验证 clazz 具有正在验证的属性,问题是在处理 field1 时,clazz 是 ArrayList 而不是 item(0) 的类(即 ChildClassForValidation)。
在向 Hibernate Validator 项目提交错误之前,我想确认我的发现。谁知道我的属性路径可能只是语法错误。