在某些Java泛型类型转换中类型安全警告的含义是什么? [英] What is the meaning of the type safety warning in certain Java generics casts?

查看:793
本文介绍了在某些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泛型类型转换中类型安全警告的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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