问题描述
我正在创建一个泛型类,并且在其中一种方法中我需要知道当前使用的泛型类型的类.原因是我调用的方法之一期望将其作为参数.
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.
示例:
public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}
显然上面的例子不起作用并导致以下错误:类型参数 T 的类文字非法.
Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.
我的问题是:有人知道一个好的替代方案或解决方法吗?
My question is: does someone know a good alternative or workaround for this?
推荐答案
还是一样的问题: 通用信息在运行时被擦除,无法恢复.一种解决方法是在静态方法的参数中传递类 T:
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
public class MyGenericClass<T> {
private final Class<T> clazz;
public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
return new MyGenericClass<U>(clazz);
}
protected MyGenericClass(Class<T> clazz) {
this.clazz = clazz;
}
public void doSomething() {
T instance = clazz.newInstance();
}
}
它很丑,但很管用.
这篇关于如何确定泛型类型的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!