I want to write a custom validation annotation that will work with multiple types. I know generics can be used but I cant use generics because I need to call a method on the type that is passed to the validator class.
so I want to have
@MyAnnotation
public class RequestA{
private MyObject myObject;
private String value;
}
and another class with same annotation
@MyAnnotation
public class RequestB{
private MyObject myObject;
private String value;
}
@Documented
@Constraint(validatedBy = MyAnnotationValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidHoursRequested {
String message() default "The value is null or missing";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and the validator needs to look like this
public class RequestedHoursValidator implements ConstraintValidator<MyAnnotation, ???> {
public void initialize(MyAnnotation constraint) {
}
@Override
public boolean isValid(??? request, ConstraintValidatorContext context) {
if (request.getMyObject().checkWahtever()) {
return request.getValue() != null;
}
return true;
}
}
The problem is that ???, is there a way to pass something dynamic to the validator. I can do this by implementing a market interface but I am looking for something more built in framework or the proper way of doing it.
Thanks
you can not define generic class so you need to use Object instead of that
therefor i assume that you check classes with ParentClass. like this:
public class ParentClass {
abstract boolean checkWahtever();
abstract Object getValue();
}
public class RequestedHoursValidator implements ConstraintValidator<MyAnnotation, Object > {
public void initialize(MyAnnotation constraint) {
}
@Override
public boolean isValid(Object request, ConstraintValidatorContext context) {
if (request instanceof ParentClass) {
ParentClass parent =request;
if (parent.checkWahtever()) {
return parent.getValue() != null;
}
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With