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

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

    I had this problem in an abstract generic class. In this particular case, the solution is simpler:

    abstract class Foo {
        abstract Class getTClass();
        //...
    }
    

    and later on the derived class:

    class Bar extends Foo {
        @Override
        Class getTClass() {
            return Whatever.class;
        }
    }
    

提交回复
热议问题