Get generic type of class at runtime

后端 未结 26 2533
野的像风
野的像风 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 04:58

    Here is my solution

    public class GenericClass
    {
        private Class realType;
    
        public GenericClass() {
            findTypeArguments(getClass());
        }
    
        private void findTypeArguments(Type t) {
            if (t instanceof ParameterizedType) {
                Type[] typeArgs = ((ParameterizedType) t).getActualTypeArguments();
                realType = (Class) typeArgs[0];
            } else {
                Class c = (Class) t;
                findTypeArguments(c.getGenericSuperclass());
            }
        }
    
        public Type getMyType()
        {
            // How do I return the type of T? (your question)
            return realType;
        }
    }
    

    No matter how many level does your class hierarchy has, this solution still works, for example:

    public class FirstLevelChild extends GenericClass {
    
    }
    
    public class SecondLevelChild extends FirstLevelChild {
    
    }
    

    In this case, getMyType() = java.lang.String

提交回复
热议问题