java - Java 5 中注释类型的编译时检查有何变化?

标签 java generics java-5

我正在查看 Java 5 中引入的更改,以下文档对我来说看起来不清楚。

<T extends Annotation> T getAnnotation(Class<T> annotationType); 

This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:

    Author a = Othello.class.getAnnotation(Author.class);

Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation.

通过使用 Annotation 作为参数类型,我仍然能够让编译器检查该参数是否表示 Annotation 的子类。我在这里缺少什么,编译时检查如何随着泛型的引入而改变?

我同意我现在不需要转换结果。

最佳答案

“...代表一个子类...”并不意味着子类的实例。在这种情况下,您可以使用 Annotation作为参数类型。相反,它意味着 Class 的一个实例对应于 Annotation 的子类.

没有泛型:

Annotation getAnnotation(Class annotationType);

您可以传递任何 Class到方法。例如:

SomeType.class.getAnnotation(Object.class);

同时Object实际上不是 Annotation 的子类型.

但是对于泛型,你有一个类型绑定(bind),并且 Class它本身有一个通用参数,即它编码的类型。

使用泛型,传递 Object.class ,其类型为 Class<Object> ,会抛出编译器错误,因为 T将是Object ,和Object不符合界限:<T extends Annotation> .

关于java - Java 5 中注释类型的编译时检查有何变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43035126/

相关文章:

java - 哪些库已移植到不同的编程语言?

Java - 搜索超过 1 个大写字母的单词

java - Android 应用程序构建错误

c# - 如何在 C# 2.0 中使用匿名泛型委托(delegate)

C# 泛型 : default non-null value for member

typescript :函数返回类型取决于输入函数返回类型

Java 版本迁移弃用日期方法

java - 使用 CSVWriter 导出带有 BLOB 的数据库表

linux - 在 Java 5 中设置文件权限

java - SEVERE : A message body writer for Java class java. 未找到 util.ArrayList 和 MIME 媒体类型 application/json