简体   繁体   English

为什么从对象转换为无界通配符集时没有警告?

[英]Why there is no warning while casting from object to unbounded wildcard collection?

Why is there no warning for the below code? 为什么以下代码没有警告?

public void some(Object a){
    Map<?, ?> map = **(Map<?,?>)a**;  //converting unknown object to map    
}

I expected the RHS to have an unchecked warning. 我预计RHS会有一个未经检查的警告。

While this code has a warning: 虽然此代码有警告:

public void some(Object a){
   Map<Object, Object> map = **(Map<Object,Object>)a**;
  //converting unknown object to Map<Object,Object>      
}

Also, for below case there is no warning: 此外,对于以下情况,没有警告:

String str = (String) request.getAttribute("asd") //returns Object

Does this mean that unchecked warnings came with generics? 这是否意味着仿制药带来了未经检查的警告? There were no such warnings before introduction of generics in Java? 在Java中引入泛型之前没有这样的警告?

Yes, the unchecked warning is only relevant to generic types. 是的,未经检查的警告仅与通用类型相关。

What it means is: this cast from Object to Map<T1, T2> might succeed because the object is indeed a Map, but the runtime has no way, due to type erasure, to check that it's a Map<T1, T2> . 这意味着:从Object到Map<T1, T2>可能会成功,因为该对象确实是一个Map,但由于类型擦除,运行时无法检查它是否为Map<T1, T2> It might very well be a Map<T3, T4> . 它可能很适合Map<T3, T4> So you might very well break the type-safety of the map by putting T1, T2 elements inside, or get a ClassCastException when trying to read values from the map. 因此,您可以通过在内部放置T1,T2元素来破坏映射的类型安全性,或者在尝试从映射中读取值时获取ClassCastException。

You have no warning for the first cast because you're casting to a Map<?, ?> , which means that the key and the value type is unknown, which is true. 你没有警告第一次投射,因为你正在转换为Map<?, ?> ,这意味着键和值类型是未知的,这是真的。 You won't be able to perform a type-unsafe operation on such a map without additional casts: you can't add anything to such a map, and the only thing you can get out of it is instances of Object . 如果没有额外的强制转换,你将无法在这样的地图上执行类型不安全的操作:你不能向这样的地图添加任何东西,你唯一可以得到的就是Object实例。

You get no "unchecked" warning because the cast is completely "checked" -- a cast to Map<?,?> only needs to ensure that the object is a Map (and nothing else), and that is completely checkable at runtime. 你没有得到“未经检查”的警告,因为强制转换被“检查” - 对Map<?,?>强制转换只需要确保对象是Map (没有别的),并且在运行时完全可以检查。 In other words, Map<?,?> is a reifiable type. 换句话说, Map<?,?>是可再生类型。

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

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