0

I found a similar question and answer -> How can I validate two or more fields in combination?

But I want to make it reusable way without using inheritance.

For example, I want to write an annotation that checks that end date must be greater than start date.

class A {
    Date startDate;
    Date endDate;
}

class B {
    Date startDate;
    Date endDate;
}

According to the answer I linked, I need to write 2 separate annotations. How can I do it with single annotation?

eghnacr
  • 129
  • 7

1 Answers1

0

You can use reflection to get fields value.

  1. In example you linked you need to add 2 fields to @AddressAnnotation:
  • startDateFieldName
  • endDateFieldName
  1. Store them in MultiCountryAddressValidator in initialize method.
  2. Change implements ConstraintValidator<AddressAnnotation, Address> to implements ConstraintValidator<AddressAnnotation, Object>
  3. In isValid method use reflection to get actual values of start and end date.
talex
  • 17,973
  • 3
  • 29
  • 66
  • Thanks for your answer. Is it the best and clean way? The point I insist on is actually not annotation. I'm trying to do with the cleanest way. – eghnacr Aug 04 '21 at 18:47
  • @Bose Probably yes. Or create some superclass with parent date-fields for A and B classes, so you can use this superclass in Validator. In other case you can't be sure which class you're going to check and how fields will be named in it. – Alexey Gorelik Aug 05 '21 at 20:21