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

前端 未结 22 1245
猫巷女王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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 12:04

    Imagine you have an abstract superclass that is generic:

    public abstract class Foo {}
    

    And then you have a second class that extends Foo with a generic Bar that extends T:

    public class Second extends Foo {}
    

    You can get the class Bar.class in the Foo class by selecting the Type (from bert bruynooghe answer) and infering it using Class instance:

    Type mySuperclass = myFoo.getClass().getGenericSuperclass();
    Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
    //Parse it as String
    String className = tType.toString().split(" ")[1];
    Class clazz = Class.forName(className);
    

    You have to note this operation is not ideal, so it is a good idea to cache the computed value to avoid multiple calculations on this. One of the typical uses is in generic DAO implementation.

    The final implementation:

    public abstract class Foo {
    
        private Class inferedClass;
    
        public Class getGenericClass(){
            if(inferedClass == null){
                Type mySuperclass = getClass().getGenericSuperclass();
                Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
                String className = tType.toString().split(" ")[1];
                inferedClass = Class.forName(className);
            }
            return inferedClass;
        }
    }
    

    The value returned is Bar.class when invoked from Foo class in other function or from Bar class.

提交回复
热议问题