使用场景
- 持久化保存
- 进程间通信
- 网络传输对象
使用方式
Serialize
只需要继承Serializable这个接口,Serializable是个空接口,用于标记这是个可序列化的对象。serialVersionUID用于标记序列化和反序列化对象的版本号,不写的话编译时会自动给一个。
public class Person implements Serializable { private static final long serialVersionUID = -7060210544600464482L; private String name; private int age; public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } }
对Serializable对象的具体处理在ObjectOutputStream的writeObject方法中
Paracale
Parcelabl用起来比较麻烦,需要自己重写序列化方法writeToParcel方法和反序列化CREATOR对象
public class Book implements Parcelable { private String bookName; private String author; private int publishDate; public Book(){ } public String getBookName(){ return bookName; } public void setBookName(String bookName){ this.bookName = bookName; } public String getAuthor(){ return author; } public void setAuthor(String author){ this.author = author; } public int getPublishDate(){ return publishDate; } public void setPublishDate(int publishDate){ this.publishDate = publishDate; } @Override public int describeContents(){ return 0; } @Override public void writeToParcel(Parcel out, int flags){ out.writeString(bookName); out.writeString(author); out.writeInt(publishDate); } public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>(){ @Override public Book[] newArray(int size){ return new Book[size]; } @Override public Book createFromParcel(Parcel in){ return new Book(in); } }; public Book(Parcel in){ //如果元素数据是list类型的时候需要: lits = new ArrayList<?> in.readList(list); //否则会出现空指针异常.并且读出和写入的数据类型必须相同.如果不想对部分关键字进行序列化,可以使用transient关键字来修饰以及static修饰. bookName = in.readString(); author = in.readString(); publishDate = in.readInt(); } }
工作原理
- Paracale在JAVA层和C层都实现了Paracale方法,最终都是在C层用malloc分配内存,适合IPC等内存间高速通信的场景,不适用于把对象保存在硬盘上
- Serializable实现简单不需要额外的代码,但是会产生很多中间变量,频繁触发GC