The spec. doesn't make it clear what the expected behaviour of the system is with regard to ConstraintValidator resolution for arrays of primitive types, e.g. int[].
- Should arrays of primitive types be converted to arrays of the primitive type wrappers (this could get expensive)?
- Should they only match ConstraintValidators that have been configured for the specific type (or Object). This would be most in-keeping with the language spec. but would mean that there would have to be many implementations of validators for constraints such as Size (or the validator for Object would need to use value.getClass().isArray() and then do the right thing).
Then there is also the question of what the behaviour should be for arrays of arrays: for example, you might want to have a constraint of the 2d-size of an array.
In the 4.0.0.Alpha3 release of the reference implementation, all arrays (whether primitive or Object) seem to be treated as Array.class for resolution purposes. Everything, then comes crashing down (i.e. a ClassCastException is raised) when trying to call the isValid method of a validator (such as SizeValidatorForArray) that expects an Object[] and an int[] is provided.
Code:
public class TestHibernateValidatorOnPrimitiveArray {
private static final class BeanWithIntArray {
@Size(min = 5, max = 10)
private int[] intArray;
public int[] getIntArray() {
return intArray;
}
public void setIntArray(int[] intArray) {
this.intArray = intArray;
}
}
@Test
public void testHibernateValidatorOnArray() {
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator v = vf.getValidator();
BeanWithIntArray object = new BeanWithIntArray();
object.setIntArray(new int[0]);
Set<ConstraintViolation<BeanWithIntArray>> cv = v.validate(object);
System.out.println(cv);
}
}
Code:
java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
at org.hibernate.validation.constraints.SizeValidatorForArray.isValid(SizeValidatorForArray.java:31)
at org.hibernate.validation.engine.ConstraintTree.validateConstraints(ConstraintTree.java:119)
at org.hibernate.validation.engine.MetaConstraint.validateConstraint(MetaConstraint.java:126)
at org.hibernate.validation.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:262)
at org.hibernate.validation.engine.ValidatorImpl.validateConstraints(ValidatorImpl.java:237)
at org.hibernate.validation.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:189)
at org.hibernate.validation.engine.ValidatorImpl.validate(ValidatorImpl.java:110)