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

后端 未结 1 1740
遥遥无期
遥遥无期 2021-01-17 07:47

I\'m using Java 1.6.0_25.

I have an annotation defined:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Resource {
           


        
相关标签:
1条回答
  • 2021-01-17 07:48

    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
    
    0 讨论(0)
提交回复
热议问题