Get generic type of class at runtime

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

    As others mentioned, it's only possible via reflection in certain circumstances.

    If you really need the type, this is the usual (type-safe) workaround pattern:

    public class GenericClass {
    
         private final Class type;
    
         public GenericClass(Class type) {
              this.type = type;
         }
    
         public Class getMyType() {
             return this.type;
         }
    }
    

提交回复
热议问题