Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java validation: type level annotation for multiple types

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

like image 792
Toseef Zafar Avatar asked Sep 11 '26 09:09

Toseef Zafar


1 Answers

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;
        }
}
like image 165
amir azizkhani Avatar answered Sep 13 '26 01:09

amir azizkhani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!