首页 > 技术文章 > Parcelable序列化对象

diysoul 2016-04-16 17:40 原文


一.序列化的目的
永久性保存对象,保存对象的字节序列到本地文件中;
通过序列化对象在网络中传递对象;
通过序列化在进程间传递对象;
在Intent中进行传递复杂自定义类对象时,需要实现Parcelable接口.

二.实现序列化的方法及优缺点比较
1.实现Serializable接口,不需要实特定的接口,相当于对象打了一个标记,系统会自动将其序列化.
优点: 可将数据存储在磁盘
缺点: 在Android系统中,序列化时会产生大量的临时变量引起频繁的GC.
2.实现Parcelable接口,为Android特有,需要按照一定的规范来实现.
Parcelable接口通过writeToParcel方法将对象映射为Parcel对象,再通过内部类对象CREATOR的方法createFromParcel将Parcel对象映射到特定的对象.
其中writeToParcel和createFromParcel必须实现,并且读写的顺序必须保持一致.
优点: 在内存中操作,性能高.
缺点: 外界有变化时不能很好的保证数据的持续性,因此不能用这种方法将数据保存到磁盘中.

三.Parcelable接口使用方法
实现Parcelable接口, 实现以下方法
public int describeContents()
public void writeToParcel(Parcel dest, int flags)
假设新的类为T,实现构造方法
public T(Parcel in)
定义静态内部对象CREATOR实现接口Parcelable.Creator, 其中public static final都不能缺少,CREATOR全为大写不能变.格式如下
public static final Parcelable.Creator<T> CREATOR
实例如下,
public static final Parcelable.Creator<T> CREATOR = new Creator<T>() {

@Override
public T[] newArray(int size) {
return new T[size];
}

@Override
public T createFromParcel(Parcel source) {
return new T(source);
}
};
PS: createFromParcel方法实现从Parcel中读取数据,封装成Parcelable对象返回逻辑层.
newArray返回一个类型为T的数组,供外部反序列化本类数组使用.

四.代码示例

 

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {

    private long mId;
    private int mAge;
    private String mName;
    private String mAddress;
    public Object mExtra;

    public Person(long id, int age, String name, String Address, Object extra) {
        mId = id;
        mAge = age;
        mName = name;
        mAddress = Address;
        mExtra = extra;
    }

    public Person(Parcel in) {
        mId = in.readLong();
        mAge = in.readInt();
        mName = in.readString();
        if (in.readByte() == 1) {
            mExtra = in.readParcelable(getClass().getClassLoader());
        }
        mAddress = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(mId);
        dest.writeInt(mAge);
        dest.writeString(mName);

        Parcelable p = null;
        if (mExtra != null) {
            try {
                p = (Parcelable) mExtra;
            } catch (ClassCastException e) {
                p = null;
            }
        }
        if (p != null) {
            dest.writeByte((byte) 1);
            dest.writeParcelable(p, flags);
        } else {
            dest.writeByte((byte) 0);
        }

        dest.writeString(mAddress);
    }

    public static final Parcelable.Creator<Person> CREATOR = new Creator<Person>() {

        @Override
        public Person[] newArray(int size) {
            return new Person[size];
        }

        @Override
        public Person createFromParcel(Parcel source) {
            return new Person(source);
        }
    };
}   

 






推荐阅读