我正在查看 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 ofAnnotation
.
通过使用 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/