Get generic type of class at runtime

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

    Here's one way, which I've had to use once or twice:

    public abstract class GenericClass{
        public abstract Class getMyType();
    }
    

    Along with

    public class SpecificClass extends GenericClass{
    
        @Override
        public Class getMyType(){
            return String.class;
        }
    }
    

提交回复
热议问题