在某些Java泛型类型转换中类型安全警告的含义是什么?

编程入门 行业动态 更新时间:2024-10-25 12:27:35
本文介绍了在某些Java泛型类型转换中类型安全警告的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

? 实际上检查已擦除类型List

当我试图将一个对象转换为类型的通用信息时,如下面的代码:

Object object = getMyList(); List< Integer> list =(List< Integer>)object;

解决方案

此警告存在,因为Java实际上并不存储类型运行时在使用泛型的对象中的信息。因此,如果 object 实际上是 List< String> ,将不会有 ClassCastException ,除非从列表中访问了与变量中定义的泛型类型不匹配的项目。

如果将项目添加到列表中,并且使用此不正确的通用类型信息,这可能会导致更多的复杂性。任何仍然保持对列表的引用但具有正确的通用类型信息的代码现在将具有不一致的列表。

要移除警告,请尝试:

列表<?> ; list =(List<?>)object;但是,请注意,您将无法使用某些方法,例如添加,因为编译器没有使用$知道你是否试图添加不正确类型的对象。上面的工作在很多情况下,但如果你必须使用add,或一些类似的限制方法,你只需要忍受黄色下划线在Eclipse(或 SuppressWarning 注释)。

What is the meaning of the Java warning?

Type safety: The cast from Object to List is actually checking against the erased type List

I get this warning when I try to cast an Object to a type with generic information, such as in the following code:

Object object = getMyList(); List<Integer> list = (List<Integer>) object;

解决方案

This warning is there because Java is not actually storing type information at run-time in an object that uses generics. Thus, if object is actually a List<String>, there will be no ClassCastException at run-time except until an item is accessed from the list that doesn't match the generic type defined in the variable.

This can cause further complications if items are added to the list, with this incorrect generic type information. Any code still holding a reference to the list but with the correct generic type information will now have an inconsistent list.

To remove the warning, try:

List<?> list = (List<?>) object;

However, note that you will not be able to use certain methods such as add because the compiler doesn't know if you are trying to add an object of incorrect type. The above will work in a lot of situations, but if you have to use add, or some similarly restricted method, you will just have to suffer the yellow underline in Eclipse (or a SuppressWarning annotation).

更多推荐

在某些Java泛型类型转换中类型安全警告的含义是什么?

本文发布于:2023-11-25 17:25:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630668.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   含义   在某些   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!