使用类对象作为泛型类型 [英] Using class object as generic type
问题描述
我不确定如何问这个问题,这也是为什么我不确定标题等的原因。
I'm not entirely sure of how to ask this question, which is also why I'm not sure about the title and so on. Here goes.
假设您有一个对象 Foo foo = new Foo()
。是否可以编写类似 new ArrayList< foo.getClass()>()
的代码,在运行时等效于 new ArrayList< Foo> ;()
?
Say you have a object Foo foo = new Foo()
. Is it possible to write code like new ArrayList<foo.getClass()>()
, which would on runtime be equivalent to new ArrayList<Foo>()
?
另一个但相关的问题是:假设类 Foo
扩展 Exception
。那么是否可以编写类似
Another, but related question is: Suppose that the class Foo
extends Exception
. Is it then possible to write something like
try{
// ...
} catch(foo.getClass() e) {
//
}
转换为
try{
// ...
} catch(Foo e) {
//
}
?
这是否很可怕,不是重要的部分。但是,无论如何,我还是想听听有约束力的意见。
Whether this would be horrible to do, is not the important part. However, I would like to hear qualified opinions anyway.
推荐答案
不,这在Java语言规范中是不可能的。泛型参数纯粹是一种编译时类型安全机制,因此在运行时定义它们是毫无意义的。
No, this is not possible in the Java language specification. Generic parameters are purely a compile-time type-safety mechanism, so defining them at runtime is non-sensical.
代码中的类文字不能与<$ c互换使用$ c> Class< T> 对象,由于其固有的不同作用。后者仅在运行时具有含义,并且可以动态变化。
Class literals in the code are not interchangeable with Class<T>
objects, due to their inherently different roles. The latter only has meaning at runtime, and can vary dynamically.
这篇关于使用类对象作为泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!