为什么Class.getAnnotation()要求我进行演员表? [英] Why is Class.getAnnotation() requiring me to do a cast?

查看:1112
本文介绍了为什么Class.getAnnotation()要求我进行演员表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java 1.6.0_25。

I'm using Java 1.6.0_25.

我有一个定义的注释:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Resource {
    String value();
}

以后当我使用getAnnotation时:

And later when I use getAnnotation:

Resource resource = (Resource)cls.getAnnotation(Resource.class);

编译器和IDE同意我必须转换结果,但getAnnotation在Java 1.5文档中声明as:

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);

由于Resource.class是Class类型,在我看来这意味着cls.getAnnotation( Resource.class)应该返回类型Resource,我应该需要强制转换。

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.

我使用getAnnotation找到的所有示例都没有强制转换,所以我必须是做错了。

All examples I've found using getAnnotation don't have a cast, so I must be doing something wrong.

推荐答案

cls 的类型是什么?它是原始 Class 还是 Class< Something>

What is the type of cls? Is it raw Class or is it Class<Something>?

如果是原始类型 Class ,则必须进行强制转换。如果您至少 Class<?> 而不是 Class ,则不再需要演员。

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

这篇关于为什么Class.getAnnotation()要求我进行演员表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆