为什么getAnnotation不接受Class <! - ?扩展注释 - >

时间:2012-05-19 09:24:31

标签: java generics annotations javac

为什么后续行在Java中产生编译错误?或者我如何编写正确的泛型语法?

Class<? extends Annotation> annotation = annotations[i];
Class<? extends Annotation> anno = javaClass.getAnnotation(annotation);

该方法的签名是:

public <A extends Annotation> A getAnnotation(Class<A> annotationClass)

从Eclipse编译错误:

Type mismatch: cannot convert from capture#5-of ? extends Annotation to Class<? extends Annotation>

从javac编译错误:

incompatible types
    Class<? extends Annotation> anno = javaClass.getAnnotation(annotation);
                                                              ^
 required: Class<? extends Annotation>
 found:    CAP#1
 where CAP#1 is a fresh type-variable:
   CAP#1 extends Annotation from capture of ? extends Annotation

1 个答案:

答案 0 :(得分:6)

getAnnotation返回注释本身 - 而不是注释的。我怀疑你可以使用:

Class<? extends Annotation> annotationClass = annotations[i];
Annotation annotation = javaClass.getAnnotation(annotationClass);