I was wondering if there is a way in Java to do something like
Class c = List.class;
Class c2 = List.class;
I nee
No, it is not possible. You can't even refer to List
in your code - it results in a compilation error. There is only one single class object for List
, and it is called List.class
.
Is this not possible because of type erasure during runtime ?
Correct.
Btw this is a generic type, not an annotated type.
On second thought, you can have something fairly close to your Map above, by tweaking Josh Bloch's typesafe heterogenous container (published in Effective Java 2nd Ed., Item 29) a bit:
public class Lists {
private Map, List>> lists =
new HashMap, List>>();
public void putList(Class type, List list) {
if (type == null)
throw new NullPointerException("Type is null");
lists.put(type, list);
}
public List getList(Class type) {
return (List)lists.get(type);
}
}
The cast in getList
is unchecked, giving a warning, but I am afraid we can't avoid that. However, we know that the value stored for class X
must be a List
, as this is guaranteed by the compiler. So I think the cast is safe (if you play by the rules, that is - i.e. never call putList
with a plain nongeneric Class
parameter), thus it can be suppressed using @SuppressWarnings("unchecked")
.
And you can use it like this:
Lists lists = new Lists();
List integerList = new ArrayList();
List stringList = new ArrayList();
...
lists.putList(Integer.class, integerList);
lists.putList(String.class, stringList);
List storedList = lists.getList(Integer.class);
assertTrue(storedList == integerList);