如何确定泛型类的类? [英] How to determine the class of a generic type?
问题描述
我正在创建一个泛型类,并且在我需要知道当前正在使用的泛型类的一个方法中。原因是我调用的方法之一期望这是一个参数。
示例:
public class MyGenericClass< T> {
public void doSomething(){
// Snip ...
//调用第三方lib
T bean =(T)someObject.create(T.class );
// Snip ...
}
}
显然上面的示例不起作用,并导致以下错误:类型参数T的非法类文字。
我的问题是:是否有人知道一个好的替代方案或解决方法解决方案仍然是相同的问题:通用信息在运行时被擦除,它不能被恢复。解决方法是在静态方法的参数中传递类T:
pre $ public $ MyGenericClass< T> {
private final Class< T> clazz中;
public static< U> MyGenericClass< U> createMyGeneric(Class< U> clazz){
返回新的MyGenericClass< U>(clazz);
}
protected MyGenericClass(Class< T> clazz){
this.clazz = clazz;
public void doSomething(){
T instance = clazz.newInstance();
$ b
这很丑陋,但它起作用。
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.
Example:
public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}
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?
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();
}
}
It's ugly, but it works.
这篇关于如何确定泛型类的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!