Get generic type of class at runtime

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

    I found this to be a simple understandable and easily explainable solution

    public class GenericClass {
    
        private Class classForT(T...t) {
            return t.getClass().getComponentType();
        }
    
        public static void main(String[] args) {
            GenericClass g = new GenericClass();
    
            System.out.println(g.classForT());
            System.out.println(String.class);
        }
    }
    

提交回复
热议问题