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

后端 未结 8 1421
北荒
北荒 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:18

    There are no Class literals for parameterized types, however there are Type objects that correctly define these types.

    See java.lang.reflect.ParameterizedType - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html

    Google's Gson library defines a TypeToken class that allows to simply generate parameterized types and uses it to spec json objects with complex parameterized types in a generic friendly way. In your example you would use:

    Type typeOfListOfFoo = new TypeToken>(){}.getType()
    

    I intended to post links to the TypeToken and Gson classes javadoc but Stack Overflow won't let me post more than one link since I'm a new user, you can easily find them using Google search

提交回复
热议问题