Get generic type of class at runtime

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

    I used follow approach:

    public class A {
    
        protected Class clazz;
    
        public A() {
            this.clazz = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    
        public Class getClazz() {
            return clazz;
        }
    }
    
    public class B extends A {
       /* ... */
        public void anything() {
           // here I may use getClazz();
        }
    }
    

提交回复
热议问题