0

Is it possible to write @SomeAnnotation(..) class annotation so that it could control inner (class fields )annotations ?

@SomeAnnotation(s1notNull = true|false, s2pattern = "xyz|smth", s3notNull = true|false, s3pattern = "123| smth")
class c1 {
  @NotNull
  @Conditional..(..) // to control @NotNull
  String s1;

  @Pattern(regexp = s2pattern) 
  String s2;

  @NotNull 
  @Conditional..(..) // to control @NotNull
  @Pattern(regexp = s3pattern) 
  String s3;
}

user16547619
  • 199
  • 1
  • 4
  • [Annotations don't _do_ anything](https://stackoverflow.com/questions/18189980/how-do-annotations-like-override-work-internally-in-java/18202623). You can certainly write your code that interprets annotations to consider this kind of composition, but note that if you're specifically looking at Bean Validation you're operating under its rules. – chrylis -cautiouslyoptimistic- Jul 28 '21 at 16:19
  • Are you using Bean Validation? If so, you can create your own constraint but that's likely more work than just putting the individual annotations on each field. But note what you're showing in your example is illegal Java. An annotation can't refer to the elements of another annotation. The code processing the annotations could probably be coded in a way you want, but you can't just do `regexp = s3pattern`. – Slaw Jul 28 '21 at 16:20
  • No, not beans, for Valid + Validation checks – user16547619 Jul 28 '21 at 17:20
  • After some thinking, it looks more promising to create a custom validator for this purpose, like : http://dolszewski.com/java/custom-parametrized-validation-annotation/ – user16547619 Jul 28 '21 at 21:24
  • Just to note, I believe "Valid + Validation checks" is still part of the _Bean Validation_ specification. – Slaw Jul 29 '21 at 13:40

0 Answers0