Java Generic Type and Reflection
- by Tom Tucker
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.