作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些涉及反射的棘手泛型类型问题。这是代码。
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)
如果我删除通配符,则它可以编译并正常工作。为 vairable validatorClass 声明类型参数的正确方法是什么?
谢谢。
最佳答案
? extends Annotation
表示“注释的未知子类型”,它不同于“注释的任何子类型”。
该方法的初始化需要“注释的未知子类型”,表示在某些时候未知子类型现在被称为 AnotherAnnotation
,并且您试图传递 Annotation 类的对象,但该对象可能不会是 AnotherAnnotation
的类型,因此它们不兼容。
类似问题的回答here .
关于Java 泛型类型和反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551067/
我是一名优秀的程序员,十分优秀!