Serialiable和Parceble的使用

Serializable

使用

1
2
3
4
5
6
7
public class User implements Serializable {
private static final long serialVersionUID = 2737236472349823L;

public int userId;
public String userName;
public boolean isMale;
}

类实现Serializable接口,即可自动实现序列化过程。

serialVersionUID标识可以指定,也可以不指定。serialVersionUID用来辅助序列化和反序列化过程,序列化后的数据中的serialVersionUID只有和当前类的serialVersionUID相同,才可以被正常反序列化。若不指定,编辑器根据当前类的结构自动生成hash值作为serialVersionUID,但若类发生变化时,比如增加或删除某些成员变量,系统自动重新计算hash值并赋值给serialVersionUID,这个时候当前类的serialVersionUID和序列化数据的serialVersionUID不一致,反序列会失败。(目前使用中好像没发现这个问题,为什么???)

重写序列化和反序列化过程

1
2
3
4
5
6
7
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// write 'this' to 'out'...
}

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
// populate the fields of 'this' from the data in 'in'...
}

transient关键字:加上transient关键字的变量,不会被序列化。

Parcelable接口

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class User implements Parcelable {
public int userId;
public String userName;
public boolean isMale;

public Book book;

public User(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}

// 内容描述
public describeContents() {
return 0;
}

// 序列化过程
public void writeToParcel(Parcel out, int flags) {
out.writeInt(userId);
out.writeString(userName);
out.writeInt(isMale ? 1 : 0 ); // boolean不能序列化,只能转化成int
out.writeParcelable(book, 0);
}

// 反序列化过程
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}

public User[] newArray(int size) {
return new User[size];
}
};

private User(Parcel in) {
userId = in.readInt();
userName = in.readString();
isMale = in.readInt() == 1;
book = in.readParcelable(Thread.currentThread().getContextClassLoader());
}

}

Parcelable的方法说明

方法 功能 标记位
createFromParcel(Parcel in) 从序列化的对象中创建原始对象
newArray(int size) 创建指定长度的原始对象数组
User(Parcel in) 从序列化的对象中创建原始对象
writeToParcel(Parcel out, int flags) 将当前对象写入序列化结构中,flags有0和1两种,为1标识当前对象需要作为返回值返回,不能立即释放资源,几乎所有情况都为0 PARCELABLE_WRITE_RETURN_VAL
describeContents 返回当前对象的内容描述。如果含有文件描述符,返回1,否则返回0,几乎所有情况都返回0 CONTENTS_FILE_DESCRIPTOR

区别

Serializable是Java中的序列化接口,使用起来简单但开销大,需要大量的I/0操作。Parcelable是Android中的序列化方式,更适合在Android平台上使用,虽然使用起来稍微麻烦,但是效率高。

0%