类< T>的通用性质是什么?意思?什么是T? [英] What does the generic nature of the class Class<T> mean? What is T?
问题描述
当涉及到集合时,我理解泛型。但是在 Class< T>
类的情况下是什么意思?当你实例化一个 Class
对象时,只有一个对象。那么为什么 T
参数?它指定什么?
类型参数< T>
java.lang.Class
以启用一个特定的成语 1 - 使用类
对象作为类型安全对象工厂。基本上,添加< T>
可以以类型安全的方式实例化类,例如: T instance = myClass.newInstance();
类型参数< T>
类本身,通过在通用类中存储类< T>
或将其作为参数传递给通用方法,可以避免类型擦除的不愉快影响。注意 T
本身不足以完成此任务 2 : T
被擦除,所以它变成 java.lang.Object
。
这是一个经典的例子其中< T>
类的参数变得重要。在下面的示例中,Java编译器能够确保类型安全性,允许您从SQL字符串和类< T>
的实例生成类型化集合。请注意,该类用作工厂,并且其类型安全性可以在编译时验证:
public static< T>集合< T> select(Class< T> c,String sqlStatement){
Collection< T> result = new ArrayList< T>();
/ *运行sql查询使用jdbc * /
for(/ * iterate over jdbc results * /){
T item = c.newInstance();
/ *使用反射,并从sql结果中设置所有项目的字段* /
result.add(item);
}
return result;因为Java会删除类型参数,使它成为一个
}
$ b < java.lang.Object 或指定为泛型上限的类别,访问 select
方法中的 Class< T>
对象很重要。由于 newInstance
返回类型< T>
的对象,编译器可以执行类型检查, / p>
1
2 这不同于没有类型擦除的泛型的实现,例如.NET中的一种。
3 Oracle的泛型教程。
I understand generics when it comes to collections. But what does it mean in the case of the Class<T>
class? When you instantiate a Class
object, there's only one object. So why the T
parameter? What is it specifying? And why is it necessary (if it is)?
Type parameter <T>
has been added to java.lang.Class
to enable one specific idiom1 - use of Class
objects as type-safe object factories. Essentially, the addition of <T>
lets you instantiate classes in a type-safe manner, like this:
T instance = myClass.newInstance();
Type parameter <T>
represents the class itself, enabling you to avoid unpleasant effects of type erasure by storing Class<T>
in a generic class or passing it in as a parameter to a generic method. Note that T
by itself would not be sufficient to complete this task2: the type of T
is erased, so it becomes java.lang.Object
under the hood.
Here is a classic example where <T>
parameter of the class becomes important. In the example below, Java compiler is able to ensure type safety, letting you produce a typed collection from a SQL string and an instance of Class<T>
. Note that the class is used as a factory, and that its type safety can be verified at compile time:
public static <T> Collection<T> select(Class<T> c, String sqlStatement) {
Collection<T> result = new ArrayList<T>();
/* run sql query using jdbc */
for ( /* iterate over jdbc results */ ) {
T item = c.newInstance();
/* use reflection and set all of item’s fields from sql results */
result.add(item);
}
return result;
}
Since Java erases the type parameter, making it a java.lang.Object
or a class specified as the generic's upper bound, it is important to have access to the Class<T>
object inside the select
method. Since newInstance
returns an object of type <T>
, the compiler can perform type checking, eliminating a cast.
1
2 This is different from implementations of generics without type erasure, such as one in .NET.
3 Java Generics tutorial by Oracle.
这篇关于类< T>的通用性质是什么?意思?什么是T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!