Java泛型 - 获取类? [英] Java generics - get class?
本文介绍了Java泛型 - 获取类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个列表,程序如下:public class MyList
.有什么方法可以使用 T 变量来获取类的名称(这样我就可以从 MyList
中知道 T 是 String、Socket 等)吗?
I got a list, programmed like this: public class MyList<T>
. Is there any way to use the T variable to get the name of class (so I can, from within MyList
, know if T is String, Socket, etc.)?
没关系,在这里找到答案.
推荐答案
简短回答:你不能.
长答案:
由于泛型在 Java 中的实现方式,泛型类型 T 不会在运行时保留.不过,您可以使用私有数据成员:
Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:
public class Foo<T>
{
private Class<T> type;
public Foo(Class<T> type) { this.type = type; }
}
使用示例:
Foo<Integer> test = new Foo<Integer>(Integer.class);
这篇关于Java泛型 - 获取类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文