How do I get a class instance of generic type T?

前端 未结 22 1259
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  [愿得一人]
    2020-11-21 12:02

    I have an (ugly but effective) solution for this problem, which I used recently:

    import java.lang.reflect.TypeVariable;
    
    
    public static  Class getGenericClass()
    {
        __ ins = new __();
        TypeVariable[] cls = ins.getClass().getTypeParameters(); 
    
        return (Class)cls[0].getClass();
    }
    
    private final class __ // generic helper class which does only provide type information
    {
        private __()
        {
        }
    }
    

提交回复
热议问题