如何投射 List<Object>到列表<MyClass> [英] How to cast List&lt;Object&gt; to List&lt;MyClass&gt;

查看:27
本文介绍了如何投射 List<Object>到列表<MyClass>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不能编译,任何建议表示赞赏.

This does not compile, any suggestion appreciated.

 ...
  List<Object> list = getList();
  return (List<Customer>) list;

编译器说:无法将 List 转换为 List

Compiler says: cannot cast List<Object> to List<Customer>

推荐答案

您始终可以通过先将任何对象向上转换为 Object 来将其转换为任何类型.在你的情况下:

you can always cast any object to any type by up-casting it to Object first. in your case:

(List<Customer>)(Object)list; 

您必须确保在运行时列表只包含 Customer 对象.

you must be sure that at runtime the list contains nothing but Customer objects.

批评者说这样的转换表明你的代码有问题;您应该能够调整您的类型声明以避免它.但是Java泛型太复杂了,还不够完美.有时你只是不知道是否有一个很好的解决方案来满足编译器,即使你非常了解运行时类型并且你知道你正在尝试做什么是安全的.在这种情况下,只需根据需要进行粗铸,这样您就可以下班回家.

Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.

这篇关于如何投射 List<Object>到列表<MyClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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