Java – call .class on a generic type in Java


I was wondering if there is a way in Java to do something like

Class c = List<String>.class;
Class c2 = List<Date>.class;

I need something like this to create a map that stores the class name (with generic type) and the corresponding object which I can later lookup. For example,

Map<Class, Object> dataMap = new HashMap<Class, Object>();
dataMap.put(c, listOfStrings);
dataMap.put(c2, listOfDates);

Is this not possible because of type erasure during runtime ?

Best Solution

You can't to it quite like this, but you can achieve your overall aim using the same approach as Guice does with TypeLiteral. If you're using Guice already, I suggest you use that directly - otherwise, you might want to create your own similar class.

Essentially the idea is that subclasses of a generic type which specify type arguments directly retain that information. So you write something like:

TypeLiteral literal = new TypeLiteral<List<String>>() {};

Then you can use literal.getClass().getGenericSuperclass() and get the type arguments from that. TypeLiteral itself doesn't need to have any interesting code (I don't know whether it does have anything in Guice, for other reasons).