我不明白为什么会发生这种ClassCastException [英] I don't get why this ClassCastException occurs

查看:173
本文介绍了我不明白为什么会发生这种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

为什么转换为 Uri [] 中断,当 Uri Parcelable

Why does the cast to Uri[] break, when Uri is 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.

原因是类型为Safety, JVM 简单地无法确保您的数组的内容可以转换为Uri,而不必通过它们进行迭代,这就是为什么您必须迭代它们并单独转换它们。

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 可以被其他对象继承,所以不能保证数组只包含 Uri 对象。但是,转换为超类型将起作用,因为类型安全性是可以的。

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天全站免登陆