概述
- 序列化:将数据结构或对象转换成可用于存储或传输的数据格式的过程,在序列化期间,数据结构或对象将其状态信息写入到临时或持久性存储中;
- 反序列化:将序列化生成 的数据还原成数据结构或对象的过程。
性能比较
对比 | Parcelable | Serializable |
---|---|---|
实现方式 | 实现Parcelable接口 | 实现Serializable接口 |
属于 | android 专用 | Java自带 |
内存消耗 | 优秀 | 一般 |
读写数据 | 内存中直接进行读写 | 通过使用IO流的形式将数据读写入在硬盘上 |
持久化 | 不可以 | 可以 |
速度 | 优秀 | 一般 |
Serializable
Serializable 是JDK提供的接口,序列化方式是基于磁盘或网络的。Serializable 接口是一种标识接口,也就是无需实现方法,便能实现序列化。
缺点:使用反射机制,在序列化过程中产生很多临时文件,容易触发垃圾回收,序列化的过程比较慢。
序列化过程中使用 serialVersionUID 的版本号和序列化的类关联,如果序列化和反序列化的UID不同,会报 InvalidClassException 异常;解决方式是显式指定 UID(IDE 为我们随机生成)。
/**
* 直接实现 Serializable 接口完成序列化
*/
public class ZpSerializableBean implements Serializable{
private static final long serialVersionUID = 9165010654231l;
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Parcelable
Parcelable 是Android SDK 提供的,它是基于内存的,速度快;一般Android 中跨进程对象的传递 一般使用 Parcelable。
缺点:需要生成大量的模板代码。可以使用Studio 的插件 Android Parcelable code generator ,一键生成模板代码。
public class ZpParcelableBean implements Parcelable {
private int id;
private String name;
public ZpParcelableBean() {
}
// 接口内容的描述,一般默认返回0
@Override
public int describeContents() {
return 0;
}
// 序列化的方法,将类的数据写入到 Parcel 容器中
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
}
// Parcel内部包装了可序列化的数据,可以在Binder中自由传输。 从序列化后的对象中创建原始对象。
protected ZpParcelableBean(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
}
// 反序列化功能是由CREATOR来完成,其内部标明了如何创建序列化对象和数组,
// 并通过Parcel的一些了read方法来完成反序列化过程。
public static final Parcelable.Creator<ZpParcelableBean> CREATOR = new Parcelable.Creator<ZpParcelableBean>() {
// 反序列化方法,将 Parcel 还原成 Java 对象
@Override
public ZpParcelableBean createFromParcel(Parcel source) {
return new ZpParcelableBean(source);
}
// 提供给外部类反序列化这个数组使用
@Override
public ZpParcelableBean[] newArray(int size) {
return new ZpParcelableBean[size];
}
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
比较
- Serializable用起来简单,但开销很大,序列化和反序列化过程都需要大量的I/O操作。
- Parcelable是Android中的序列化方式,更适合在Android平台上使用,用起来比较麻烦,效率很高,首选。主要用在内存序列化上
数据传递
- Parcelable
// 传递数据
Bundle bundle = new Bundle();
//Parcelable 系列化对象
bundle.putSerializable("person_data",person);
intent.putExtras(bundle);
---------------------------------------------------------
// 获得数据
Person person =(Person) getIntent().getParcelableExtra("person_data")
- Serializable
// 传递数据
intent.putExtra("person_data",person);
---------------------------------------------------------
// 获得数据
Person person = (Person)getIntent().getSerializableExtra("person_data");
网友评论