简体   繁体   中英

Java unchecked operation cast to generic

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.

PS I don't want to get rid of the warning, I want to understand the unsafe operation.

Thanks!

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, eg by iterating over the entries and fetching the key and value.

Welcome to the wacky world of Java generics :(

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM