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

前端 未结 22 1232
猫巷女王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:01

    If you are extending or implementing any class/interface that are using generics , you may get the Generic Type of parent class/interface, without modifying any existing class/interface at all.

    There could be three possibilities,

    Case 1 When your class is extending a class that is using Generics

    public class TestGenerics {
        public static void main(String[] args) {
            Type type = TestMySuperGenericType.class.getGenericSuperclass();
            Type[] gTypes = ((ParameterizedType)type).getActualTypeArguments();
            for(Type gType : gTypes){
                System.out.println("Generic type:"+gType.toString());
            }
        }
    }
    
    class GenericClass {
        public void print(T obj){};
    }
    
    class TestMySuperGenericType extends GenericClass {
    }
    

    Case 2 When your class is implementing an interface that is using Generics

    public class TestGenerics {
        public static void main(String[] args) {
            Type[] interfaces = TestMySuperGenericType.class.getGenericInterfaces();
            for(Type type : interfaces){
                Type[] gTypes = ((ParameterizedType)type).getActualTypeArguments();
                for(Type gType : gTypes){
                    System.out.println("Generic type:"+gType.toString());
                }
            }
        }
    }
    
    interface GenericClass {
        public void print(T obj);
    }
    
    class TestMySuperGenericType implements GenericClass {
        public void print(Integer obj){}
    }
    

    Case 3 When your interface is extending an interface that is using Generics

    public class TestGenerics {
        public static void main(String[] args) {
            Type[] interfaces = TestMySuperGenericType.class.getGenericInterfaces();
            for(Type type : interfaces){
                Type[] gTypes = ((ParameterizedType)type).getActualTypeArguments();
                for(Type gType : gTypes){
                    System.out.println("Generic type:"+gType.toString());
                }
            }
        }
    }
    
    interface GenericClass {
        public void print(T obj);
    }
    
    interface TestMySuperGenericType extends GenericClass {
    }
    

提交回复
热议问题