Getting generic parameter from supertype class

后端 未结 3 1554
死守一世寂寞
死守一世寂寞 2021-01-21 06:56

Say I have a parent interface/class like so

interface Parent {}

And a number of implementing interfaces that fix the generic type.

3条回答
  •  既然无缘
    2021-01-21 07:26

    Yes, despite what the others have said, this info is available if you have access to the subclass' Class object. You need to use getGenericSuperclass along with getActualTypeArguments.

    ParameterizedType superClass = (ParameterizedType)childClass.getGenericSuperclass();
    System.out.println(superClass.getActualTypeArguments()[0]);
    

    In your example, the "actual" type argument should return the Class for Type.

提交回复
热议问题