Knowing type of generic in Java

后端 未结 7 1146
醉话见心
醉话见心 2020-12-03 16:17

I have a generic class, says :

MyClass

Inside a method of this class, I would like to test the type of T, for example :

         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 16:49

    Because of type erasure you can't... mostly. But there is one exception to that. Consider:

    class A {
      List list;
    }
    
    public class Main {
      public static void main(String args[]) {
        for (Field field : A.class.getDeclaredFields()) {
          System.out.printf("%s: %s%n", field.getName(), field.getGenericType());
        }
      }
    }
    

    Output:

    list: java.util.List
    

    If you need the class object, this is how you generally handle it:

    public  T createObject(Class clazz) {  
      return clazz.newInstance();
    }
    

    ie by passing the class object around and deriving the generic type from that class.

提交回复
热议问题