Java: how do I get a class literal from a generic type?

后端 未结 8 1319
北荒
北荒 2020-11-22 07:18

Typically, I\'ve seen people use the class literal like this:

Class cls = Foo.class;

But what if the type is generic, e.g. List?

8条回答
  •  既然无缘
    2020-11-22 08:16

    You could use a helper method to get rid of @SuppressWarnings("unchecked") all over a class.

    @SuppressWarnings("unchecked")
    private static  Class generify(Class cls) {
        return (Class)cls;
    }
    

    Then you could write

    Class> cls = generify(List.class);
    

    Other usage examples are

      Class> cls;
    
      cls = generify(Map.class);
    
      cls = TheClass.>generify(Map.class);
    
      funWithTypeParam(generify(Map.class));
    
    public void funWithTypeParam(Class> cls) {
    }
    

    However, since it is rarely really useful, and the usage of the method defeats the compiler's type checking, I would not recommend to implement it in a place where it is publicly accessible.

提交回复
热议问题