Android序列化

Android序列化包括两种:Java的Serializable、Android自己的Parcelable。推荐使用Android系统自带的Parcelable。

Serializable方式

只需使对象实现Serialzable接口即可

假设Person类已经实现 Serializable接口

  • 传输Person对象
 intent.putExtra("person_data", person);
  • 接收序列化对象
Person person = (Person) getIntent().getSerializableExtra("person_data");

Parcelable方式

Parcel :This class is designed as a high-performance IPC transport

Parcelable方式是把对象写成Parcel(小包),核心的类其实是Parcel。Parcelable定义的一系列接口就是是把对象分解成Parcel、把Parcel还原为对象。

Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a non-null static field called CREATOR of a type that implements the Parcelable.Creator interface.

Parcelable除了该实现的抽象方法(分解对象为Parcel),还要必须要包含一个非空静态域,叫做CREATOR(把Parcel还原为对象)

public class Person implements Parcelable {
            private String name;
            private int age;
            ……
            @Override
            public int describeContents() {
                return 0;
            }
            //写出对象为Parcel
            @Override
            public void writeToParcel(Parcel dest, int flags) {
                dest.writeString(name); //  写出name
                dest.writeInt(age); //  写出age
            }
            //非空静态域,还原Parcel为对象
            public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
                @Override
                //从Parcel还原
                public Person createFromParcel(Parcel source) {
                    Person person = new Person();
                    person.name = source.readString(); //  读取name
                    person.age = source.readInt(); //  读取age
                    return person;
                }
                @Override
                public Person[] newArray(int size) {
                    return new Person[size];
                }
            };
        }
  • 传输Person对象
 intent.putExtra("person_data", person);
  • 接收序列化对象
Person person = (Person) getIntent().getParcelableExtra("person_data");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值