我不明白为什么这个ClassCastException异常发生 [英] I dont get why this ClassCastException occurs

查看:249
本文介绍了我不明白为什么这个ClassCastException异常发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Application ...
Intent i = new Intent();
i.putExtra(EXTRA_FILE_UPLOAD_URIS, mGalleryAdapter.getItems()); 

Uri[] getItems() { return mItems; }

// Service ...
intent.getParcelableArrayExtra(EXTRA_FILE_UPLOAD_URIS); //works, returns Parcelable[]
Uri[] uris = (Uri[])intent.getParcelableArrayExtra(EXTRA_FILE_UPLOAD_URIS);
// ... Breaks with ClassCastException

为什么要转换成开放的[] 休息的时候,乌里 Parcelable

推荐答案

不幸的是没有办法施展这样的阵列的Java 。你将不得不遍历您的阵列和单独投的每个对象。

Unfortunately there is no way to cast like that for arrays in Java. You will have to iterate your array and cast each object individually.

这样做的原因是类型安全,在 JVM 根本无法确保您的阵列中的内容可以被强制转换为开放的,而不必重复通他们,这是你为什么要遍历他们并将他们的个人。

The reason for this is type Safety, the JVM simply cannot ensure that the contents of your array can be casted to Uri, without having to iterate thru them, which is why you have to iterate them and cast them individually.

基本上是因为 Parcelable 可以由其他对象继承,也不能保证该数组只包含乌里对象。但是强制转换为超会起作用,因为再键入安全将是确定。

Basically because Parcelable could be inherited by other Objects, there is no guarantee that the Array contains only Uri objects. However casting to a supertype would work since then type safety would be ok.

这篇关于我不明白为什么这个ClassCastException异常发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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