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

前端 未结 22 1309
猫巷女王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 11:53

    That is pretty straight forward. If you need from within the same class:

    Class clazz = this.getClass();
    ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
    try {
            Class typeClass = Class.forName( parameterizedType.getActualTypeArguments()[0].getTypeName() );
            // You have the instance of type 'T' in typeClass variable
    
            System.out.println( "Class instance name: "+  typeClass.getName() );
        } catch (ClassNotFoundException e) {
            System.out.println( "ClassNotFound!! Something wrong! "+ e.getMessage() );
        }
    

提交回复
热议问题