Parcelable
Parcelable是一個(gè)接口,只要實(shí)現(xiàn)這個(gè)接口,該類的對(duì)象就可以實(shí)現(xiàn)序列化。
序列化:由writeToParcel方法來完成,通過Parcel中的一系列write方法來完成。
public class User implements Parcelable {
public int userId;
public String userName;
public boolean isMale;
public Book book; // Book是一個(gè)類
public User(int userId , String userName , boolean isMale){
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}
//實(shí)現(xiàn)內(nèi)容描述
//幾乎所有情況都返回0
//僅在當(dāng)前對(duì)象中存在文件描述時(shí)返回1
public int describeContents () {
return 0;
}
//實(shí)現(xiàn)序列化,通過Parcel的各種write方法實(shí)現(xiàn)
public void writeToParcel(Parcel out, int flags) {
out.writeInt(userId);
out.writeString(userName);
out.writeInt(isMale ? 1: 0);
out.writeParcelable(book, 0);
}
//實(shí)現(xiàn)反序列化
//在CREATOR(Parcelable.Creator<T>)中標(biāo)明如何創(chuàng)建序列化對(duì)象和數(shù)組
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];
}
};
//通過Parcel 的一系列read方法來實(shí)現(xiàn)反序列化
private User(Parcel in) {
userId = in.readInt();
userName = in.readString();
isMale = in.readInt() == 1;
book = in.readParcelable(Thread.currentThread().getContextClassLoader());
}
}
Serializable
Java提供的序列化接口,是一個(gè)接口。
使用Serializable實(shí)現(xiàn)序列化很簡單,只需要實(shí)現(xiàn)Serializable接口。
public class User implements Serializable{
private static final long serialVersionUID = 14566565484854856L;
public int userId;
public String userName;
public boolean isMale;
}
差異
Serializable實(shí)現(xiàn)序列化比Parcelable開銷要大,但實(shí)現(xiàn)起來簡單。