I'm using Java 1.6.0_25.
I have an annotation defined:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Resource {
String value();
}
And later when I use getAnnotation:
Resource resource = (Resource)cls.getAnnotation(Resource.class);
the compiler and IDE agree that I must cast the result, but getAnnotation is declared in the Java 1.5 documentation as:
public <A extends Annotation> A getAnnotation(Class<A> annotationClass);
Since Resource.class is of type Class, it seems to me that this means that cls.getAnnotation(Resource.class) should return type Resource, and I should need to cast.
All examples I've found using getAnnotation don't have a cast, so I must be doing something wrong.
The getAnnotation() method of java. lang. Class class is used to get the annotation of the specified annotation type, if such an annotation is present in this class. The method returns that class in the form of an object.
What is the type of cls
? Is it raw Class
or is it Class<Something>
?
If it's the raw type Class
, then the cast is necessary. If you make it at least Class<?>
instead of Class
, you won't need the cast anymore.
Class cls = Example.class;
// Error: Type mismatch, cannot convert from Annotation to Resource
Resource anno = cls.getAnnotation(Resource.class);
Class<?> cls2 = Example.class;
Resource anno = cls2.getAnnotation(Resource.class); // OK
Class<Example> cls3 = Example.class;
Resource anno = cls3.getAnnotation(Resource.class); // OK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With