Get generic type of class at runtime

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

    One simple solution for this cab be like below

    public class GenericDemo{
        private T type;
    
        GenericDemo(T t)
        {
            this.type = t;
        }
    
        public String getType()
        {
            return this.type.getClass().getName();
        }
    
        public static void main(String[] args)
        {
            GenericDemo obj = new  GenericDemo(5);
            System.out.println("Type: "+ obj.getType());
        }
    }
    

提交回复
热议问题