Android序列化Serializable和Parcelable的理解和区别

文章目录

    • 序列化
    • 序列化方式
    • 区别
        • Parcelable(Android专用):
        • Serializable(Java拥有)

序列化

序列化是将一个对象转换成可存储或可传输的状态。序列化后的对象可以在网络上进行传输,也可以存储到本地。

序列化方式

Android中使用Intent传递对象时,需要使用到序列化
方式一:Serializable,Java Bean直接实现Serializable接口
方式二:Parcelable,Java Bean实现Parcelable接口,并实现接口方法

区别

Parcelable(Android专用):

实现相对麻烦,通过分解对象,将每个数据转换成Intent支持的类型。一般只使用在Intent跳转,效率高,不易保存在磁盘中

public class TestParcelable implements Parcelable{
    private String name;
    private int age;
    private boolean isDebug;

    public TestParcelable(String name, int age, boolean isDebug) {
        this.name = name;
        this.age = age;
        this.isDebug = isDebug;
    }

    protected TestParcelable(Parcel in) {
        name = in.readString();
        age = in.readInt();
        isDebug = in.readByte() != 0;
    }

    public static final Creator CREATOR = new Creator() {
        @Override
        public TestParcelable createFromParcel(Parcel in) {
            return new TestParcelable(in);
        }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isDebug() {
        return isDebug;
    }

    public void setDebug(boolean debug) {
        isDebug = debug;
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
        dest.writeByte((byte) (isDebug ? 1 : 0));
    }
}

Serializable(Java拥有)

实现超级简单,实现Serializable接口,不需要实现任何方法。会产生大量临时变量,但多用于网络、本地存储(ObjectOutputStream)

public class TestSerializable implements Serializable{
    private String name;
    private int age;
    private boolean isDebug;

    public TestSerializable(String name, int age, boolean isDebug) {
        this.name = name;
        this.age = age;
        this.isDebug = isDebug;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isDebug() {
        return isDebug;
    }

    public void setDebug(boolean debug) {
        isDebug = debug;
    }
}

你可能感兴趣的:(Android)