Search code examples
javareflectiongeneric-programming

Java Generic Type and Reflection


I have some tricky generic type problem involving reflection. Here's the code.

public @interface MyConstraint {
    Class<? extends MyConstraintValidator<?>> validatedBy();
}

public interface MyConstraintValidator<T extends Annotation> {
    void initialize(T annotation);
}

/**
    @param annotation is annotated with MyConstraint.
*/
public void run(Annotation annotation) {
    Class<? extends MyConstraintValidator<? extends Annotation>> validatorClass = annotation.annotationType().getAnnotation(MyConstraint.class).validatedBy();
    validatorClass.newInstance().initialize(annotation) // will not compile!
}

The run() method above will not compile because of the following error.

The method initialize(capture#10-of ? extends Annotation) in the type MyConstraintValidator<capture#10-of ? extends Annotation> is not applicable for the arguments (Annotation)

If I remove the wild cards, then it compiles and works fine. What would be the propert way to declare the type parameter for the vairable validatorClass?

Thanks.


Solution

  • ? extends Annotation means "unknown subtype of Annotation" which is different from "any subtype of Annotation".

    The initialization of the method requires "unknown subtype of Annotation", says at some point the unknown subtype is now known as AnotherAnnotation, and you are trying to pass an object of Annotation class which may not be the type of AnotherAnnotation so they are imcompatible.

    Similar question was answer here.