Using Parcelable with circular references

前端 未结 2 2081
梦如初夏
梦如初夏 2021-02-04 16:47

It appears that Parcelable doesn\'t gracefully handle circular references like Serializable does. In the following example, the Serialization of Bar works just fine, but writin

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 17:25

    Use Java serialization. Make your class extend Externalizable instead of Parcelable and convert it to byte array using ObjectOutputStream. Pass this byte array to other side [1] [2] and deserialize it using ObjectInputStream.

    Android Parcelables are very fast, but that speed comes at cost of all extra functionality, traditionally present in serialization frameworks.

    Java serialization was designed to be powerful and flexible and includes support for many things including handling circular references. If you declare custom serialVersionUID (to avoid it's reflective computation at runtime) and manually read/write class contents in readExternal/writeExternal, you will get almost same performance as with Parcelable (where "almost" is spent on keeping track of circular references and such).

提交回复
热议问题