Java未经检查的操作已转换为泛型 [英] Java unchecked operation cast to generic

查看:371
本文介绍了Java未经检查的操作已转换为泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么以下内容会发出有关不安全/未经检查的操作的警告:

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.我不想摆脱警告,我想了解不安全的操作.

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

谢谢!

推荐答案

这意味着强制类型转换将检查返回的对象是否是某种Map,但将无法检查其内容,原因是类型擦除.在执行时,一个映射就是一个映射就是一个映射...因此,如果有人将Map<Integer, String>放到您的会话中,那一行代码仍然会成功.当您尝试使用其中一项时,您只会得到一个错误,例如通过遍历条目并获取键和值.

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.

欢迎来到古怪的Java泛型世界:(

Welcome to the wacky world of Java generics :(

这篇关于Java未经检查的操作已转换为泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆