如何获得泛型类型T的类实例 [英] How to get a class instance of generics type T
问题描述
我有一个泛型类, 使用 简短的回答是,没有办法找到Java中泛型类型参数的运行时类型。我建议阅读 Java教程中有关删除类型的章节。更多细节。 一个流行的解决方案是将类型参数的 I have a generics class, What is the preferred way to get around it using The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the Java Tutorial for more details. A popular solution to this is to pass the
这篇关于如何获得泛型类型T的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! Foo< T>
。在 Foo
的方法中,我想获得类型T的类实例,但我不能调用 T.class $ c
T.class
?避开它的首选方法是什么?
Class
传递给构造函数泛型类型,例如
class Foo< T> {
final Class< T> typeParameterClass;
public Foo(Class< T> typeParameterClass){
this.typeParameterClass = typeParameterClass;
$ b $ public void bar(){
//你可以在这里访问typeParameterClass并做任何你喜欢的事情
}
}
Foo<T>
. In a method of Foo
, I want to get the class instance of type T, but I just can't call T.class
.T.class
?Class
of the type parameter into the constructor of the generic type, e.g.class Foo<T> {
final Class<T> typeParameterClass;
public Foo(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
public void bar() {
// you can access the typeParameterClass here and do whatever you like
}
}