【发布时间】:2011-11-25 11:59:42
【问题描述】:
如何将参数化的 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;
}
}
}
这可能吗?
【问题讨论】:
-
看看 Google Gson 的
TypeTokengoogle-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/…。它是开源的,可以解决您遇到的同样问题。 -
谢谢你,BalusC。首先,我很欣慰我没有错过一些简单的东西。但我还没有准备好解决这个问题,因为在我的应用程序中处理 Type 而不是 Class 看起来很困难。