/** * Create new constraint. The following rules are used: * <ul> * <li>use default constructor if exist.</li> * <li>otherwise, use constructor with ValidationContext parameter.</li> * </ul> */ protected <V extends ValidationConstraint> V newConstraint(final Class<V> constraint, final Class targetType) throws Exception { Constructor<V> ctor; try { ctor = constraint.getConstructor(); return ctor.newInstance(); } catch (NoSuchMethodException ignore) { ctor = constraint.getConstructor(ValidationContext.class); return ctor.newInstance(resolveFor(targetType)); } }
/** * Validate object using context from the annotations. */ public List<Violation> validate(final Object target) { return validate(ValidationContext.resolveFor(target.getClass()), target); }
@Test void testResolveFor() throws Exception { //when //Class ForCheck1 contains two fields. field1 has two constraints. Second field2 has a non constraint annotation ValidationContext context = ValidationContext.resolveFor(ClassForCheck1.class); //then assertEquals(context.map.size(), 1, "context must return a map with one element when resolve an object which has one field with constraint annotations"); assertNotNull(context.map.get("field1"), "context must return a map with key field1 when resolve an object which has field with name field1 and constraint annotations"); assertNull(context.map.get("field2"), "context must not return a map with key field2 when resolve an object which has a field with name field2 without constraint annotations"); assertEquals(context.map.get("field1").size(), 2, "context must return a map with two checks when resolve an object which has a field with two constraint annotations"); }
/** * Create new constraint. The following rules are used: * <li>use default constructor if exist. * <li>otherwise, use constructor with ValidationContext parameter. */ protected <V extends ValidationConstraint> V newConstraint(Class<V> constraint, Class targetType) throws Exception { Constructor<V> ctor; try { ctor = constraint.getConstructor(); return ctor.newInstance(); } catch (NoSuchMethodException ignore) { ctor = constraint.getConstructor(ValidationContext.class); return ctor.newInstance(resolveFor(targetType)); } }
/** * Validate object using context from the annotations. */ public void validate(Object target) { validate(ValidationContext.resolveFor(target.getClass()), target); }