I use the .class
-operator to supply information about the contained type to a generic class. For non-generic contained types, e.g. Integer.class
,
Class<List<Integer>> tListInt3 =
(Class<List<Integer>>) ((Class<Integer>)List.class);
that doesn't work. you probably meant
Class<List<Integer>> tListInt3 =
(Class<List<Integer>>) ((Class)List.class);
we can always cast from one type to another by up-cast then down-cast
Integer x = (Integer)(Object)"string";
The type of List.class
is Class<List>
; it is not a subtype/supertype of Class<List<Whatever>>
therefore direct cast between the two types is illegal.
It can be argued that Class<List<Integer>>
doesn't exist - there is only a class for List
; there is no such class for List<Integer>
(which really is just List
at runtime)
However, this is a flaw of Java type system; in practice we do need things like Class<List<Integer>>
. Our solution - casting and pretending Class<List<Int>>
exits - is likewise flawed - but it's not our fault.