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

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

    It's possible:

    class Foo {
      Class clazz = (Class) DAOUtil.getTypeArguments(Foo.class, this.getClass()).get(0);
    }
    

    You need two functions from hibernate-generic-dao/blob/master/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java.

    For more explanations, see Reflecting generics.

提交回复
热议问题