为什么 Java 的 Class<T> 是泛型的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1094023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:37:01  来源:igfitidea点击:

Why is Java's Class<T> generic?

javagenerics

提问by ripper234

Why is Java's Class<T>generic?

为什么Java是Class<T>泛型的?

采纳答案by Steve B.

So that generic typed methods can be used -

以便可以使用泛型类型方法 -

Class<Foo> klass = Foo.class;
Foo f = klass.newInstance();
Foo f = klass.cast(Object);

回答by Chris Arguin

回答by Bill the Lizard

There's a short mention of this in the Genericssection of the 1.5 version of the language guide:

在 1.5 版语言指南的泛型部分中简短地提到了这一点:

More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:

更令人惊讶的是,Class Class 已经被泛型化了。类文字现在用作类型标记,提供运行时和编译时类型信息。这启用了一种静态工厂样式,例如新 AnnotatedElement 接口中的 getAnnotation 方法:

<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:

这是一个通用的方法。它从其参数推断其类型参数 T 的值,并返回 T 的适当实例,如以下代码段所示:

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

在使用泛型之前,您必须将结果强制转换为 Author。此外,您将无法让编译器检查实际参数是否代表 Annotation 的子类

回答by Jér?me Verstrynge

The real reason is given by Neil Gafter:

真正的原因是Neil Gafter给出的:

When we added generics to Java in JDK5, I changed the class java.lang.Class to become a generic type. For example, the type of String.class is now Class < String > . Gilad Bracha coined the term type tokens for this. My intent was to enable a particular style of API, which Joshua Bloch calls the THC, or Typesafe Heterogenous Container pattern.

当我们在JDK5中为Java添加泛型时,我将类java.lang.Class更改为泛型类型。例如, String.class 的类型现在是 Class < String > 。Gilad Bracha 为此创造了术语类型标记。我的意图是启用一种特定风格的 API,Joshua Bloch 将其称为 THC,或 Typesafe Heterogenous Container 模式。