Java Generic Type and Reflection
Posted
by
Tom Tucker
on Stack Overflow
See other posts from Stack Overflow
or by Tom Tucker
Published on 2010-12-29T02:30:47Z
Indexed on
2010/12/29
2:54 UTC
Read the original article
Hit count: 229
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.
© Stack Overflow or respective owner