Get generic type of class at runtime

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

    Java generics are mostly compile time, this means that the type information is lost at runtime.

    class GenericCls
    {
        T t;
    }
    

    will be compiled to something like

    class GenericCls
    {
       Object o;
    }
    

    To get the type information at runtime you have to add it as an argument of the ctor.

    class GenericCls
    {
         private Class type;
         public GenericCls(Class cls)
         {
            type= cls;
         }
         Class getType(){return type;}
    }
    

    Example:

    GenericCls instance = new GenericCls(String.class);
    assert instance.getType() == String.class;
    

提交回复
热议问题