Android读取Parcelable数组时出现ClassNotFoundException怎么解决?
异常原因
- 读写Parcel的方法不匹配:你在
writeToParcel()中使用writeTypedArray()写入Item数组,但是在构造方法中使用readParcelableArray()读取,二者序列化存储的格式存在差异,导致Parcel解析时无法读取到正确的类名,最终抛出类找不到的异常,这也是你错误日志里ClassNotFoundException后类名为空的直接原因。 - 额外排查点:需确认Item类已经正确实现Parcelable接口,包含公开的
CREATOR静态常量,且Item的Parcel读写属性顺序完全一致。
解决方案
将构造方法中读取数组的逻辑替换为和写入配对的Typed数组读取方法,直接使用Item类的CREATOR进行反序列化,不需要额外传入类加载器,不会出现类找不到的问题:
protected ItemList(Parcel in) { // 替换原来的readParcelableArray代码,和writeTypedArray配对 Item[] itemArray = in.createTypedArray(Item.CREATOR); this.set = parcelableArrayToHashSet(itemArray); this.listUuid = UUID.fromString(in.readString()); this.creatorUuid = UUID.fromString(in.readString()); this.name = in.readString(); }
对应的转换方法也可以同步调整避免强转,可选优化:
private HashSet<Item> parcelableArrayToHashSet(Item[] items) { HashSet<Item> itemSet = new HashSet<>(); if (items != null) { Collections.addAll(itemSet, items); } return itemSet; }
改完后序列化反序列化的格式完全对齐,即可解决异常。
内容的提问来源于stack exchange,提问作者TraversingOnTarget
相关产品推荐
相关产品推荐

