如何在Java泛型中获取类型变量的类 [英] How to get the class of type variable in Java Generics
本文介绍了如何在Java泛型中获取类型变量的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我见过类似的问题,但他们没有太多帮助。
例如我有这个通用类: public class ContainerTest< T>
{
public void doSomething()
{
//我想在这里确定类型参数的类(在这种情况下为String)
}
}
以及使用此Container类的另一个类
public class TestCase
{
private ContainerTest< String> containerTest;
public void someMethod()
{
containerTest.doSomething();
是否可以确定类型参数的类在ContainerTest Class中,doSomething()没有具有显式类型变量/字段或任何构造函数的方法吗?
更新:更改了ContainerTest Class的格式
解决方案
唯一的方法是将类存储在实例变量并要求它作为构造函数的参数:
public class ContainerTest< T>
{
private Class< T> tClass;
public ContainerTest(Class< T> tClass){
this.tCLass = tClass;
}
public void doSomething()
{
// access tClass here
}
}
I've seen similar questions but they didnt help very much.
For instance I've got this Generic Class:
public class ContainerTest<T>
{
public void doSomething()
{
//I want here to determinate the Class of the type argument (In this case String)
}
}
and Another Class which uses this Container Class
public class TestCase
{
private ContainerTest<String> containerTest;
public void someMethod()
{
containerTest.doSomething();
}
}
Is it possible to determinate the Class of the type argument in method doSomething() without having an explicit type variable/field or any constructor in ContainerTest Class?
Update: Changed format of ContainerTest Class
解决方案
The only way is to store the class in an instance variable and require it as an argument of the constructor:
public class ContainerTest<T>
{
private Class<T> tClass;
public ContainerTest(Class<T> tClass) {
this.tCLass = tClass;
}
public void doSomething()
{
//access tClass here
}
}
这篇关于如何在Java泛型中获取类型变量的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文