简体   繁体   English

Java未经检查的操作转换为泛型

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

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 . 这意味着演员将检查返回的对象是某种类型的Map ,但是由于类型擦除 ,它将无法检查其内容的任何内容。 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. 在执行时,map是map是map ...所以如果有人将Map<Integer, String>改为你的会话,那么这行代码仍然会成功。 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 :( 欢迎来到古怪的Java泛型世界:(

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). 作为程序员,您可能知道se.getSession()应该是具有<String, ProxySession>参数的精确类型,因此您正在进行转换,但它可能不是那种确切的类型(编译器建议)。 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. JVM不会像这样检查强制转换。 For example, (Map<String, ProxySession>) se.getSession().getServletContext().getAttribute("myattribute"); 例如, (Map<String, ProxySession>) se.getSession().getServletContext().getAttribute("myattribute"); will be equal to (Map) se.getSession().getServletContext().getAttribute("myattribute"); 将等于(Map) se.getSession().getServletContext().getAttribute("myattribute");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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