Java generics - retrieve type

后端 未结 6 599
忘掉有多难
忘掉有多难 2020-12-18 04:18
public Interface Foo{...}

Is there a way to retrieve which T was given for an implementation of Foo?

For example,

6条回答
  •  别那么骄傲
    2020-12-18 04:43

    Contrary to other answers, you can obtain the type of a generic parameter. For example, adding this to a method inside a generic class will obtain the first generic parameter of the class (T in your case):

    ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
    type.getActualTypeArguments()[0]
    

    I use this technique in a generic Hibernate DAO I wrote so I can obtain the actual class being persisted because it is needed by Hibernate. It works!

提交回复
热议问题