1、序列化接口
接口 | 特点 | 适用场景 |
Serializable | Java中的序列化接口,使用简单,但是开销很大。 | 将对象序列化到存储设备或将对象序列化后通过网络传输时,用Serializable较简单。 |
Parcelable | Android中的序列化方式,使用稍麻烦,但效率很高。 | 主要用于内存序列化,性能好。 |
2、Serializable接口
Serializable是一个空接口,为对象提供标准的序列化和反序列化操作。实现Serializable接口示例:
public Class User implements Serializable {
private static final long serialVersionUID = 92389236732922971L;
public int userId;
public String userName;
public boolean isMale;
}
注:
- 静态成员变量不参与序列化
- 用transient关键字标记的成员变量不参与序列化
对象的序列化和反序列化操作:
//序列化过程
User user = new User(0, "joker", true);
ObjectOutputStream out = new ObjectOutStream( new FileOutputStream("cache.txt") );
out.writeObject(user);
out.close();
//反序列化过程
ObjectInputStream in = new ObjectInputStream( new FileInputStream("cache.txt") );
User user = (User) in.readObject();
in.close();
3、Parcelable接口
Parcelable接口实现示例:
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;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.userID);
dest.writeString(this.userName);
dest.writeInt(isMale ? 1 : 0);
dest.writeParcelable(book, 0);
}
protected User(Parcel in) {
this.userID= in.readInt();
this.userName= in.readString();
this.isMale= in.readInt() == 1;
this.book= in.readParcelable(Thread.currentThread().getContextClassLoader());
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel source) {
return new User(source);
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
}
方法 | 功能 | 标记位 |
---|---|---|
createFromParcel | 从序列化后的对象中创建原始对象 | |
newArray(int size) | 创建指定长度的原始对象数组 | |
User(Parcel in) | 从序列化后的对象中创建原始对象 | |
writeToParcel(Parcel out, int flags) | 将当前对象写入序列化结构中,其中flags为标志位,1表示当前对象需要作为返回值返回,不能立即释放。一般情况都用0。 | PARCELABLE_WRITE_RETURN_VALUE |
describeContents | 返回当前对象的内容描述,如果含有文件描述符,返回1,否则返回0。一般为0。 | CONTENTS_FILE_DESCRIPTOR |