3

为什么后续行会在 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
4

1 回答 1

6

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

Class<? extends Annotation> annotationClass = annotations[i];
Annotation annotation = javaClass.getAnnotation(annotationClass);
于 2012-05-19T09:38:13.487 回答