odd behavior with java collections of parameterized Class objects
Ran into some questionable behavior using lists of parameterized Class objects:
ArrayList<Class<String>> classList = new ArrayList<Class<String>>();
classList.add(Integer.class); //compile error
Class intClass = Integer.class;
classList.add(intClass); //lega开发者_如何学Cl apparently, as long as intClass is not parameterized
Found the same behavior for LinkedList, haven't tried other collections. Is it like this for a reason? Or have I stumbled on something?
That is legal only as a concession to backward compatibility so that code written before Java 5 can be compiled in 5 or later without going through and adding generics. Using a raw type for another reason is generally considered a programming error or at least poor style/laziness.
By willfully declaring a Raw Type you're abandoning the compiler's ability to help you with type safety, so you get a warning and it's back on you to make sure things are safe at run time.
This generates an "unchecked conversion" warning.
Class
(rather than Class<String>
or Class<?>
or Class<Object>
) is a raw type. Raw types can be assigned to from parameterized types without error, but you get a warning. This type of assignment is only a warning so you can have a codebase that's only partially generified. See also the section of the JLS on raw types.
精彩评论