Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Class.getAnnotation() requiring me to do a cast?

Tags:

java

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.

like image 361
Thomas Andrews Avatar asked Feb 24 '12 15:02

Thomas Andrews


People also ask

How to get annotation from class?

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.


1 Answers

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
like image 128
Jesper Avatar answered Oct 04 '22 02:10

Jesper