我发现:
当我使用Class<?>
时声明变量,getAnnotation
充当:
public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
,但是当我使用Class
时声明变量,getAnnotation
充当:
public Annotation getAnnotation(Annotation annotationClass)
,所以我无法编译使用传递的注释类特定方法的代码。
<小时/>例如:我可以编译 ((Class<?>)clazz).getAnnotation(Human.class).age()
,但无法编译((Class)clazz).getAnnotation(Human.class).age()
,其中clazz
是一些Class
实例,和Human
是注解接口(interface),有age
方法。
最佳答案
你的问题很不清楚,但我怀疑你遇到了原始类型。
<小时/>A raw type is define to be either:
- The name of a generic type declaration used without any accompanying actual type parameters.
- Any non-static type member of a raw type R that is not inherited from a superclass or superinterface of R.
<小时/>Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables).
所以实际上就是这个方法:
public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
被删除为:
public Annotation getAnnotation(Class annotationClass)
这就是为什么您可以调用getAnnotation
,但返回类型不会是 Human
,那就是Annotation
.
关于java - 为什么 `Class` 和 `Class<?>` 的实例具有不同的行为,而它不应该如此?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7970375/