[英]Getting a Class instance corresponding to a generic type instantiation
I've got the following type: 我有以下类型:
public class GenericClass<T> {
public GenericClass(Class<T> cls) {}
}
However, I can't seem to call this when T is itself a generic class: 但是,当T本身是泛型类时,我似乎无法称之为:
GenericClass<List<String>> g = new GenericClass<>(???);
using List.class
doesn't compile, and List<String>.class
is invalid syntax. 使用
List.class
无法编译,并且List<String>.class
是无效的语法。 How can I get an instance of a Class<List<String>>
to pass to the constructor? 如何获取
Class<List<String>>
的实例传递给构造函数?
Here's an easier solution.. which totally hides the ugliness. 这是一个更简单的解决方案..这完全掩盖了丑陋。 The approach here, is to implicitly bind the result-type -- and separate that from the passed-in raw Class.
这里的方法是隐式绑定结果类型 ,并将其与传入的原始类分开。
public class GenericClass<T> {
public GenericClass(Class<T> cls) {}
// static constructor;
// - hides unchecked ugliness, & implicitly binds 'nicely typed' to result.
//
public static <T> GenericClass<T> create (Class<? super T> clazz) {
// ugly cast is hidden in here; no type checking.
Class<T> clazz_ = (Class<T>)(Class) clazz;
return new GenericClass( clazz_);
}
}
Usage: 用法:
GenericClass<List<String>> g = GenericClass.create( List.class);
I've bounded the 'passed-in Class' clazz as ? super T
我将“通过类”的界限限制为
? super T
? super T
for now, but -- if this too strict -- you can relax the bound & make the parameter just Class<?> clazz
. 现在是
? super T
,但是-如果这太严格了-您可以放宽限制并使参数仅为Class<?> clazz
。
This solution's been tested in my IDE (at least quickly) and seems to work nicely. 该解决方案已经在我的IDE中进行了测试(至少很快),并且似乎运行良好。 I'm not sure if, long-term, this is the best way to solve whatever design problem you're having -- but it definitely is the tidiest way to solve your immediate question.
从长远来看,我不确定这是否是解决您遇到的任何设计问题的最佳方法-但这绝对是解决当前问题的最简洁的方法。
How about 怎么样
GenericClass<List<String>> g =
new GenericClass<>((Class<List<String>>)(Class<?>)ArrayList.class);
You could also try declaring the constructor as follows 您也可以尝试如下声明构造函数
public <E extends T> GenericClass(Class<E> cls)
Then you can pass List.class, and any child of List, through the constructor. 然后,您可以通过构造函数传递List.class和List的任何子级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.