Java unchecked operation cast to generic

风格不统一 提交于 2019-12-10 16:43:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!