Why does getAnnotation not accept Class <? extends annotation>

Why does the follow line create a compilation error in Java? Or how can I write the correct generic syntax?

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

Method Signature:

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

Compilation error from Eclipse:

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

Compilation error from 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
+3
source share
1 answer

getAnnotationthe annotation itself returns, not the annotation class. I suspect you can just use:

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

All Articles