Get generic type of class at runtime

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

    Just in case you use store a variable using the generic type you can easily solve this problem adding a getClassType method as follows:

    public class Constant {
      private T value;
    
      @SuppressWarnings("unchecked")
      public Class getClassType () {
        return ((Class) value.getClass());
      }
    }
    

    I use the provided class object later to check if it is an instance of a given class, as follows:

    Constant constant = ...;
    if (constant.getClassType().equals(Integer.class)) {
        Constant integerConstant = (Constant)constant;
        Integer value = integerConstant.getValue();
        // ...
    }
    

提交回复
热议问题