如何确定泛型类的类? [英] How to determine the class of a generic type?

查看:118
本文介绍了如何确定泛型类的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个泛型类,并且在我需要知道当前正在使用的泛型类的一个方法中。原因是我调用的方法之一期望这是一个参数。



示例:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆