You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android:利用Parcel实现对象的深拷贝

用Parcel实现对象深拷贝:读取步骤与代码示例

你的写入代码是可行的,不过setDataPosition(0)可以省略——Parcel.obtain()返回的Parcel初始数据位置默认就是0。

要完成深拷贝,按以下步骤读取对象:

  1. 将Parcel的读取指针重置到起始位置(确保从开头读取数据)
  2. 调用readValue()方法读取对象,传入当前类的类加载器
  3. 回收Parcel资源(避免内存泄漏)

完整代码示例:

// 假设searchRequestParams的类型是YourObjectType
val copiedParams: YourObjectType? = Parcel.obtain().run {
    writeValue(searchRequestParams)
    setDataPosition(0) // 重置读取指针到起始位置
    // 读取对象并强转为目标类型,注意类型安全
    val copy = readValue(searchRequestParams.javaClass.classLoader) as? YourObjectType
    recycle() // 必须回收Parcel,释放资源
    copy
}

注意事项

  • 目标对象的类型必须是Parcelable实现类,或是Android Parcel原生支持的类型(如String、基本数据类型、ArrayList等),否则会抛出异常
  • 强转时建议用as?而非直接as,避免类型不匹配导致的ClassCastException
  • 务必调用recycle()回收Parcel,Parcel基于对象池实现,不回收会造成内存浪费

内容的提问来源于stack exchange,提问作者Gil Ong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 08:24:55