Get generic type of class at runtime

后端 未结 26 2515
野的像风
野的像风 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<T> getGenericTypeClass() {
            return (Class<T>) (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());
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:24
    public static final Class<?> getGenericArgument(final Class<?> clazz)
    {
        return (Class<?>) ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];
    }
    
    0 讨论(0)
提交回复
热议问题