如何获取一个参数化的Class对象作为方法参数?泛型:创建参数化类参数
class A<T>
{
public A(Class<T> c)
{
}
void main()
{
A<String> a1 = new A<String>(String.class); // OK
A<List<String>> a2 = new A<List<String>>(List<String>.class); // error
A<List<String>> a3 = new A<List<String>>(Class<List<String>>); // error
}
}
为什么我要这样做,你可能会问?我有一个参数化类,其类型是另一个参数化类,其构造函数要求其他类类型作为参数。我知道运行时类没有关于它们的类型参数的信息,但是这不应该阻止我在编译时这样做。看来我应该能够指定一个类型,例如List<String>.class
。是否有另一种语法来做到这一点?
这里是我的实际使用情况:
public class Bunch<B>
{
Class<B> type;
public Bunch(Class<B> type)
{
this.type = type;
}
public static class MyBunch<M> extends Bunch<List<M>>
{
Class<M> individualType;
// This constructor has redundant information.
public MyBunch(Class<M> individualType, Class<List<M>> listType)
{
super(listType);
this.individualType = individualType;
}
// I would prefer this constructor.
public MyBunch(Class<M> individualType)
{
super(/* What do I put here? */);
this.individualType = individualType;
}
}
}
这可能吗?
看看谷歌Gson的'TypeToken' http://google-gson.googlecode。 COM/SVN /中继/ GSON /文档/ javadocs中/ COM /谷歌/ GSON /反射/ TypeToken.html。它是开源的,它解决了你遇到的同样的问题。 – BalusC
[Java通用函数:如何返回泛型类型]的可能重复(http://stackoverflow.com/questions/1959022/java-generic-function-how-to-return-generic-type) – BalusC
谢谢BalusC。首先,我很安慰我不会错过简单的事情。但是我还没有准备好这样做,因为在我的应用程序中处理** Type **而不是** Class ** es看起来很困难。 –