• 欢迎访问SimonHu的博客,推荐使用360浏览器和Chrome浏览器访问本网站

How to cast List to List Object集合转换成实体集合

java SimonHu 4年前 (2017-06-30) 82次浏览 0个评论 扫描二维码
List<Object> list = getList();

return (List<Customer>) 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; 
将List<Object>强制转换成Object,然后再转换为实体集合!
地址:https://stackoverflow.com/questions/1917844/how-to-cast-listobject-to-listmyclass

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

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.

版权所有丨如未注明 , 均为原创丨
转载请注明原文链接:How to cast List to List Object集合转换成实体集合
喜欢 (0)
[]
分享 (0)
关于作者:
Do you think that guy looks like a dog???
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址