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

问题描述

这不编译,任何建议赞赏。

This does not compile, any suggestion appreciated.

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

编译器说:不能转换 List< Object> 列表< Customer>

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

推荐答案

到任何类型通过将其转换为对象首先。在您的情况下:

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&lt; Object&gt;到List&lt; MyClass&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 11:38