I have the following data class:
public abstract class Item {
@NotNull
Type getType();
void setType(Type type);
[...]
}
and corresponding subclasses for each Type (enum) value.
The validator should then check that for all (subtypes of) Item that the Type belongs to the given subclass.
The validator implementation would look roughly like this:
boolean isValid(Item item) {
return getImplClassFor(item.getType()).isAssignableFrom(item.getClass());
}
How can I register such a validator to java's default validators so that it is automatically picked up by Spring/Hibernate validator... (implementation agnostic if possible)
- spring-boot-starter-validation 2.x.x
- hibernate-validator 6.0.x
- javax.validation-api 2.1 (or later)
I cannot add any custom annotations to that class or any of it's subclasses as the datamodel is outside of my control (and generated).
Alternatives considered:
Manually checking the type as first action in each controller method: This is very error prone as it might be forgotten or accidentally removed. And is especially hard to do right for nested data structures.
Copy&Pasting the item class into the implementation and secretly adding an annotation: Since the datamodel is outside of my control I won't get notified if they ever change that class and my copy thus might become stale/incompatible.
TLDR: How do I register a ConstraintValidator for a class, that doesn't have any annotations.