问题
I am wondering why the following issues a warning about an unsafe / unchecked operation:
Map<String, ProxySession> sessionMap = (Map<String, ProxySession>) se.getSession().getServletContext().getAttribute("myattribute");
Is the cast wrong? I can't understand what I am missing here.
P.S. I don't want to get rid of the warning, I want to understand the unsafe operation.
Thanks!
回答1:
It means that the cast will check that the returned object is a Map
of some kind, but it won't be able to check anything about its contents, due to type erasure. At execution time, a map is a map is a map... so if someone put a Map<Integer, String>
into your session instead, that line of code would still succeed. You'd only get an error when you tried to use one of the entries, e.g. by iterating over the entries and fetching the key and value.
Welcome to the wacky world of Java generics :(
回答2:
It's an unchecked cast. You as a programmer may know that se.getSession() is expected to be of that exact type, with <String, ProxySession>
parameters, so you're doing the cast, but it may not be of that exact type (the compiler suggests). Since you aren't programatically checking that, the compiler warns you.
See also: How do I address unchecked cast warnings?
回答3:
JVM doesn't check casts like this.
For example, (Map<String, ProxySession>) se.getSession().getServletContext().getAttribute("myattribute");
will be equal to (Map) se.getSession().getServletContext().getAttribute("myattribute");
来源:https://stackoverflow.com/questions/7806038/java-unchecked-operation-cast-to-generic