错误地转换泛型为什么在Java中不会产生异常?

huangapple go评论62阅读模式
英文:

Why wrong casting of generics won't produce exception in java?

问题

我有这段代码:

Map<Object, Object> map;
...
List<String> strings = new ArrayList<>();
Object tmp = map.get("strings");
strings.addAll((List<String>) tmp);

如果 tmp 的类型是 List<String>,代码能够正常运行。但如果 tmp 的类型是 List<Map>,为什么程序不会抛出异常呢?

英文:

I have this code:

Map&lt;Object, Object&gt; map;
...
List&lt;String&gt; strings = new ArrayList&lt;&gt;();
Object tmp = map.get(&quot;strings&quot;);
strings.addAll((List&lt;String&gt;) tmp);

It works fine if tmp is of type List&lt;String&gt;, but why the program won't produce exception if tmp is of type List&lt;Map&gt;?

答案1

得分: 3

一个将对象强制转换为 List&lt;String&gt; 的操作实际上是将其转换为 List。在运行时,String 不再存在。IDE 确实对此发出了警告。稍后在使用 strings 项时可能会出现运行时异常。

另一件事,List&lt;Map&gt; 缺少泛型参数,当裸露地使用,比如 List list,编译器会回退到非泛型解释,消除所有关于泛型类型违规的警告。

针对您的用例:一种带有不同类型变量的简单的“变量”映射可能会有问题。请提供您自己的运行时类型信息,也许可以回退到(实际上不需要的)数据转移:

List&lt;?&gt; list = (List&lt;?&gt;) map.get("strings");
List&lt;String&gt; list2 = list.stream().map(String.class::cast).collect(Collectors.toList());
英文:

A cast to List&lt;String&gt; of an Object actually is a cast to List. At runtime String no longer is there. The IDE did warn about this. Later on when working with strings items a runtime exception may be expected.

Another thing, List&lt;Map&gt; misses generic parameters, and when used bare, like List list, the compiler reverts to non-generic interpretation, dropping all warning of generic type violations.

For your use-case: a kind of simple "variable" map with differently typed variables is problematic. Provide your own run-time type info, and maybe revert to (actually unneeded) shoveling of data:

List&lt;?&gt; list = (List&lt;?&gt;) map.get(&quot;strings&quot;);
List&lt;String&gt; list2 = list.stream().map(String.class::cast).collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年9月1日 18:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63686133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定