Get generic type of class at runtime

后端 未结 26 2608
野的像风
野的像风 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:21

    Here is working solution!!!

    @SuppressWarnings("unchecked")
        private Class getGenericTypeClass() {
            try {
                String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
                Class clazz = Class.forName(className);
                return (Class) clazz;
            } catch (Exception e) {
                throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
            }
        } 
    

    NOTES: Can be used only as superclass
    1. Has to be extended with typed class (Child extends Generic)
    OR

    2. Has to be created as anonymous implementation (new Generic() {};)

提交回复
热议问题