Java 泛型类型和反射
我有一些涉及反射的棘手泛型类型问题。这是代码。
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!
}
由于出现以下错误,上面的 run()
方法将无法编译。
The method initialize(capture#10-of ? extends Annotation) in the type MyConstraintValidator<capture#10-of ? extends Annotation> is not applicable for the arguments (Annotation)
如果我删除通配符,那么它就可以编译并正常工作。声明可用 validatorClass
的类型参数的正确方法是什么?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
<代码>? extends Annotation 表示“注释的未知子类型”,它与“注释的任何子类型”不同。
该方法的初始化需要“注释的未知子类型”,表示在某些时候未知子类型现在被称为AnotherAnnotation,并且您试图传递注释类的对象,该对象可能不是该类型
AnotherAnnotation
因此它们不兼容。类似的问题是此处的答案。
? 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 ofAnotherAnnotation
so they are imcompatible.Similar question was answer here.