序列化

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)起來簡單。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • JAVA序列化機(jī)制的深入研究 對(duì)象序列化的最主要的用處就是在傳遞,和保存對(duì)象(object)的時(shí)候,保證對(duì)象的完整...
    時(shí)待吾閱讀 10,924評(píng)論 0 24
  • Android 的序列化方式 Parcelable Parcel 介紹:Parcel 內(nèi)部包裝了可序列化的數(shù)據(jù),可...
    任教主來也閱讀 1,825評(píng)論 0 3
  • What? 何為序列化與反序列化?序列化:將對(duì)象轉(zhuǎn)化為二進(jìn)制序列的過程反序列化:將二進(jìn)制序列恢復(fù)為原始對(duì)象的過程 ...
    LilacZiyun閱讀 3,063評(píng)論 0 15
  • 很累了,全身都很臭。又怕洗完澡后沒有能量了,所以趕緊寫一寫。不知道寫什么,就寫寫今天。 我是個(gè)??粕?,畢業(yè)幾年,終...
    何kk閱讀 225評(píng)論 0 0
  • 瑋蓮 東風(fēng)夜放花千樹 冬的雪 便化作了五彩繽紛 飛舞著春天的夢 一夜間又化了春雨 融進(jìn)泥土的懷抱 杏花姑娘 梨花仙...
    驕陽下的一朵蓮閱讀 385評(píng)論 3 10