Suppose I have this in Java:
List<String> list = new ArrayList<String>();
list.getClass();
The type of the last expression is Class<? extends List>
. I understand why, due to erasure, it cannot be Class<? extends List<String>>
. But why can't it be Class<? extends List<?>>
?
Is there no way for me to avoid both unchecked cast warnings and raw type warnings if I want to assign the result of this expression to a variable that somehow keeps the information that this class is actually some kind of List
?
Class<? extends List> listClass = list.getClass(); // raw type warning
Class<? extends List<?>> listClass = (Class<? extends List<?>>) list.getClass(); // unchecked cast warning
When generics were first introduced,
getClass
returnedClass<? extends X>
, whereX
was the static type of the expression on which it was called. This behavior led to unreasonable compilation issues, as reported in this Oracle bug. Here is that bug report's example:This issue was resolved by widening the return type of
getClass
to be what it is now. From the documentation:This resolved the above issue but consequently led to the issue that your question points out. Not long after, another bug was reported, arguing the following:
This bug was not acted upon and remains open to this day, with the following counterarguments:
(abridged and with some typos corrected)
Being that
List
is an Interface, I am not sure it is possible to find out that theList
interface is implemented forArrayList
. Found this Link here that might help.I did mess around with this for a bit and found that...
but I am not sure if that is what your looking for...
Good Luck!