NumericFieldRelationValidator implements Validator { @Override public boolean validate(Object instance, Annotation annotation, Object value) { if (value == null) { return true; } RelativeToNumericField ann = RelativeToNumericField.class.cast(annotation); String fieldName = ann.field(); try { double doubleValue = Double.valueOf(value.toString()); java.lang.reflect.Field field = instance.getClass().getDeclaredField(fieldName); field.setAccessible(true); double fieldValue = Double.valueOf(field.get(instance).toString()); return relationChecker.checkDoubleRelation(doubleValue, fieldValue, ann.relation()); } catch (Exception e) { return false; } }  @Override boolean validate(Object instance, Annotation annotation, Object value); @Override Class<? extends Annotation> getAnnotationClass(); @Override String getMessage(Annotation annotation, String fieldName, Object value);  }
@Test public void testValidateDoubleField() throws Exception { TestObject instance = new TestObject(); RelativeToNumericField doubleFieldAnnotation = new RelativeToNumericField() { @Override public BooleanRelation relation() { return BooleanRelation.GREATER_THAN; } @Override public String field() { return "doubleField"; } @Override public Class<? extends Annotation> annotationType() { return RelativeToNumericField.class; } }; assertThat(validator.validate(instance, doubleFieldAnnotation, null), is(true)); assertThat(validator.validate(instance, doubleFieldAnnotation, 1), is(true)); assertThat(validator.validate(instance, doubleFieldAnnotation, -1), is(false)); }
@Test public void testValidateStringField() { TestObject instance = new TestObject(); RelativeToNumericField stringFieldAnnotation = new RelativeToNumericField() { @Override public BooleanRelation relation() { return BooleanRelation.GREATER_THAN; } @Override public String field() { return "stringField"; } @Override public Class<? extends Annotation> annotationType() { return RelativeToNumericField.class; } }; assertThat(validator.validate(instance, stringFieldAnnotation, "anything"), is(false)); }
@Test public void testValidateMissingField() { TestObject instance = new TestObject(); RelativeToNumericField missingFieldAnnotation = new RelativeToNumericField() { @Override public BooleanRelation relation() { return BooleanRelation.GREATER_THAN; } @Override public String field() { return "missingField"; } @Override public Class<? extends Annotation> annotationType() { return RelativeToNumericField.class; } }; assertThat(validator.validate(instance, missingFieldAnnotation, "anything"), is(false)); }