问题描述
我想编组和解编实现到/从字节数组实现Parcelable
的类. 我很清楚以下事实:Parcelable表示形式不稳定,因此并不意味着长期存储实例.但是我有一个用例,需要序列化一个对象,并且它不是一个展示对象.如果由于内部Android更改而导致解组失败.而且该类已经在实现Parcelable
接口.
I want to marshall and unmarshall a Class that implements Parcelable
to/from a byte array. I am well aware of the fact that the Parcelable representation is not stable and therefore not meant for long term storage of instances. But I have a use case where I need to serialize a object and it's not a showstopper if the unmarshalling fails because of an internal Android change. Also the class is already implementing the Parcelable
interface.
给定类MyClass implements Parcelable
,我如何(ab)使用Parcelable
接口进行编组/解组?
Given an class MyClass implements Parcelable
, how can I (ab)use the Parcelable
interface for marshalling/unmarshalling?
推荐答案
首先创建一个帮助器类 ParcelableUtil.java :
First create a helper class ParcelableUtil.java:
public class ParcelableUtil {
public static byte[] marshall(Parcelable parceable) {
Parcel parcel = Parcel.obtain();
parceable.writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle();
return bytes;
}
public static Parcel unmarshall(byte[] bytes) {
Parcel parcel = Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0); // This is extremely important!
return parcel;
}
public static <T> T unmarshall(byte[] bytes, Parcelable.Creator<T> creator) {
Parcel parcel = unmarshall(bytes);
T result = creator.createFromParcel(parcel);
parcel.recycle();
return result;
}
}
借助上面的util类,您可以像这样编组/解组类MyClass implements Parcelable
的实例:
With the help of the util class above, you can marshall/unmarshall instances of your class MyClass implements Parcelable
like so:
解组(使用CREATOR
)
Unmarshalling (with CREATOR
)
byte[] bytes = …
MyClass myclass = ParcelableUtil.unmarshall(bytes, MyClass.CREATOR);
解组(没有CREATOR
)
Unmarshalling (without CREATOR
)
byte[] bytes = …
Parcel parcel = ParcelableUtil.unmarshall(bytes);
MyClass myclass = new MyClass(parcel); // Or MyClass.CREATOR.createFromParcel(parcel).
编组
MyClass myclass = …
byte[] bytes = ParcelableUtil.marshall(myclass);
这篇关于如何在Parcel的帮助下将一个Parcelable编组和解组为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!