1
class A {

     private String someField;

     @validation
     private String annotatedField;
}

I'm implementing a custom constraint validation annotation @validation to validate annotatedField. I need to know the value of someField to satisfy the logic of my validation.

Validator implements ConstraintValidator<validation, String>{

      @Override
      public void initialize(validation constraintAnnotation) {

      }

      @Override
      public boolean isValid(String annotatedField, ConstraintValidatorContext context) {

           if (StringUtils.isBlank(annotatedField)) {
                return true;
           }

           String someField; // get some someField value given the annotatedField

      }
}

Is there a way to do this using reflection?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tddiaz
  • 111
  • 1
  • 3
  • 12
  • 1
    Given an object, you can reflectively determine the value of a field. There are plenty of existing resources on how to do that. Or is your question about something else? – Oliver Charlesworth Nov 27 '17 at 13:33
  • 1
    Yes it's pretty easy to know the value of `someField` using reflection; what have you tried so far, and what went wrong? https://docs.oracle.com/javase/tutorial/reflect/ – Haroldo_OK Nov 27 '17 at 13:36
  • Possible duplicate of [How to get the fields in an Object via reflection?](https://stackoverflow.com/questions/2989560/how-to-get-the-fields-in-an-object-via-reflection) –  Nov 27 '17 at 13:48
  • updated my question. – tddiaz Nov 27 '17 at 13:49
  • This problem is not a good candidate for solving via annotations. – Michael Nov 27 '17 at 13:49
  • 1
    You'd better approach this with a class-level constraint as previously referred by https://stackoverflow.com/a/2783859/1654233, for example. – yegodm Nov 27 '17 at 14:13
  • @yegodm Yes class-level constraint would be the easy solution to this. but to my case, `@validation` annotation is dedicated only for field `annotatedField`. for me, it doesnt make sense to make `@validation` annotation a class-level for a workaround. thanks – tddiaz Nov 27 '17 at 14:31
  • 1
    @tddiaz I'm afraid class-level constraint is not a easy solution or a workaround, but **the** solution provided by `javax.validation` design. There is no feature in the framework that would let you access the object owning a property when your validator target is a property. Please, also see https://stackoverflow.com/q/27007233/1654233. – yegodm Nov 27 '17 at 15:53
  • 1
    Note that you should really rename `validation` to `Validation`, per overwhelming Java convention. – Oliver Charlesworth Nov 27 '17 at 16:29

1 Answers1

0

This turns out to be not possible.

A class-level constraint annotation would be recommended to address this problem.

tddiaz
  • 111
  • 1
  • 3
  • 12