Get generic type of class at runtime

后端 未结 26 2524
野的像风
野的像风 2020-11-21 04:40

How can I achieve this?

public class GenericClass
{
    public Type getMyType()
    {
        //How do I return the type of T?
    }
}
26条回答
  •  余生分开走
    2020-11-21 05:23

    To complete some of the answers here, I had to get the ParametrizedType of MyGenericClass, no matter how high is the hierarchy, with the help of recursion:

    private Class getGenericTypeClass() {
            return (Class) (getParametrizedType(getClass())).getActualTypeArguments()[0];
    }
    
    private static ParameterizedType getParametrizedType(Class clazz){
        if(clazz.getSuperclass().equals(MyGenericClass.class)){ // check that we are at the top of the hierarchy
            return (ParameterizedType) clazz.getGenericSuperclass();
        } else {
            return getParametrizedType(clazz.getSuperclass());
        }
    }
    

提交回复
热议问题