java - 为什么 `Class` 和 `Class<?>` 的实例具有不同的行为,而它不应该如此?

标签 java compiler-construction behavior

我发现:

当我使用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方法。

最佳答案

你的问题很不清楚,但我怀疑你遇到了原始类型。

<小时/>

JLS — 4.8 Raw Types :

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.

JLS — 4.6 Type Erasure :

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/

相关文章:

java - HTTP 传输错误 : javax.net.ssl.SSLHandshakeException

java - keytool 无法加载 PKCS12 文件

java - eclipse 向导 : how to add a checkboxlist?

cakephp - 从 Controller 更改 $actsAs 变量

java - HikariPool-1 - 在连接获取期间中断

c++ - SFML 2.1 RenderWindow 链接错误

c - 在 yyparse() 调用时执行操作?

compiler-construction - opa:无法编译 hello chat 演示(另一个错误)

php - PHP 中 mysql_connect 的奇怪行为

c# - TreeView SelectedItem 行为 - 双向绑定(bind)在一个方向上不起作用