淺談Serializable和Parcelable

一蛮瞄、作用

兩者都是用于對象的序列化成二進(jìn)制的流棍郎,便于在intent或bundle中傳輸钦讳。

二阅签、區(qū)別

1. Serializable

Serializable是java的序列化接口掐暮,核心實現(xiàn)是ObjectOutPutStream.writeObject()進(jìn)行序列化,ObjectInputStream.readObject()進(jìn)行反序列化政钟。

serialVersionUID
可在序列化的類中定義serialVersionUID路克,用static和final修飾化漆,用于在反序列化中驗證類版本的差異核行。

  • 如果不定義serialVersionUID,系統(tǒng)會聲明個默認(rèn)值柜候,當(dāng)類發(fā)生變化后碎连,serialVersionUID將會被系統(tǒng)重新計算賦值灰羽,反序列化時,如果前后serialVersionUID不一致鱼辙,將會crash廉嚼,拋出InvalidClassException錯誤。
  • 如果定義serialVersionUID座每,盡管序列化后類發(fā)生變化前鹅,由于前后serialVersionUID一致,反序列化時也會盡最大的程度復(fù)原峭梳,如果復(fù)原失敗一樣會拋出InvalidClassException錯誤舰绘。

在Android Serializable 的Api注釋中有段說明:針對Android N以上版本的設(shè)備時,為了保證對之前版本的兼容性葱椭,強(qiáng)烈建議顯示的定義serialVersionUID捂寿,而不是由系統(tǒng)默認(rèn)賦值。

2. Parcelable

Parcelable是Android特有的序列化接口孵运,核心實現(xiàn)是通過parcel的讀寫操作進(jìn)行序列化秦陋,里面的方法是Native方法。

  • 使用Serializable會頻繁進(jìn)行IO操作治笨,開銷很大驳概,在Android平臺上,Parcelable多用于內(nèi)存序列化旷赖,如IPC進(jìn)程間通信顺又。

三、實現(xiàn)Parcelable步驟

public class Student implements Parcelable {

    private int id;
    private String name;
    private boolean isBoy;

    private Student(Parcel in) {
        id = in.readInt();
        name = in.readString();
        isBoy = in.readByte() != 0;
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(id);
        parcel.writeString(name);
        parcel.writeByte((byte) (isBoy ? 1 : 0));
    }
}

實現(xiàn)Parcelable必須實現(xiàn)describeContents()writeToParcel(Parcel parcel, int i)方法等孵。還需要創(chuàng)建個Parcelable.Creator接口的成員稚照,用于進(jìn)行反序列化操作。

3.1 describeContents()

方法返回當(dāng)前對象的內(nèi)容描述,如果含有文件描述符果录,則返回1上枕,一般默認(rèn)返回0。

 /**
     * Describe the kinds of special objects contained in this Parcelable
     * instance's marshaled representation. For example, if the object will
     * include a file descriptor in the output of {@link #writeToParcel(Parcel, int)},
     * the return value of this method must include the
     * {@link #CONTENTS_FILE_DESCRIPTOR} bit.
     *  
     * @return a bitmask indicating the set of special object types marshaled
     * by this Parcelable object instance.
     */
    public @ContentsFlags int describeContents();
3.2 writeToParcel(Parcel, int)

在這方法進(jìn)行序列化弱恒,falg默認(rèn)為0辨萍;如果需要對象作為返回值返回,則值為1斤彼,這樣不能立即釋放資源分瘦。

 /**
     * Flatten this object in to a Parcel.
     * 
     * @param dest The Parcel in which the object should be written.
     * @param flags Additional flags about how the object should be written.
     * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
     */
    public void writeToParcel(Parcel dest, @WriteFlags int flags);
3.3 Parcelable.Creator
 /**
     * Interface that must be implemented and provided as a public CREATOR
     * field that generates instances of your Parcelable class from a Parcel.
     */
    public interface Creator<T> {
        /**
         * Create a new instance of the Parcelable class, instantiating it
         * from the given Parcel whose data had previously been written by
         * {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
         * 
         * @param source The Parcel to read the object's data from.
         * @return Returns a new instance of the Parcelable class.
         */
        public T createFromParcel(Parcel source);
        
        /**
         * Create a new array of the Parcelable class.
         * 
         * @param size Size of the array.
         * @return Returns an array of the Parcelable class, with every entry
         * initialized to null.
         */
        public T[] newArray(int size);
    }

createFromParcel ():反序列化,創(chuàng)建原始序列化對象
newArray ():反序列化琉苇,創(chuàng)建原始序列化對象的數(shù)組
內(nèi)部通過Parcel的read方法實現(xiàn)嘲玫。

成員也需實現(xiàn)Parcelable才能保證序列化的完整
如果Student不實現(xiàn)Parcelable,那么School實現(xiàn)序列化的成員不包括Student

public class School implements Parcelable {

    private String name;
    private Student student;

    private School(Parcel in) {
        name = in.readString();
        student = in.readParcelable(Student.class.getClassLoader());
    }

    public static final Creator<School> CREATOR = new Creator<School>() {
        @Override
        public School createFromParcel(Parcel in) {
            return new School(in);
        }

        @Override
        public School[] newArray(int size) {
            return new School[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(name);
        parcel.writeParcelable(student, i);
    }
}

student = in.readParcelable(Student.class.getClassLoader())在反序列化時并扇,需要獲取當(dāng)前線程的成員類的加載器去团,否則會報找不到該類的錯誤。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末穷蛹,一起剝皮案震驚了整個濱河市土陪,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌肴熏,老刑警劉巖鬼雀,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異蛙吏,居然都是意外死亡源哩,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進(jìn)店門鸦做,熙熙樓的掌柜王于貴愁眉苦臉地迎上來励烦,“玉大人,你說我怎么就攤上這事泼诱√陈樱” “怎么了?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵治筒,是天一觀的道長屉栓。 經(jīng)常有香客問我,道長耸袜,這世上最難降的妖魔是什么系瓢? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮句灌,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己胰锌,他們只是感情好骗绕,可當(dāng)我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著资昧,像睡著了一般酬土。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上格带,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天撤缴,我揣著相機(jī)與錄音,去河邊找鬼叽唱。 笑死屈呕,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的棺亭。 我是一名探鬼主播虎眨,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼镶摘!你這毒婦竟也來了嗽桩?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤凄敢,失蹤者是張志新(化名)和其女友劉穎碌冶,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涝缝,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡扑庞,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了俊卤。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嫩挤。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖消恍,靈堂內(nèi)的尸體忽然破棺而出岂昭,到底是詐尸還是另有隱情,我是刑警寧澤狠怨,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布约啊,位于F島的核電站,受9級特大地震影響佣赖,放射性物質(zhì)發(fā)生泄漏恰矩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一憎蛤、第九天 我趴在偏房一處隱蔽的房頂上張望外傅。 院中可真熱鬧纪吮,春花似錦、人聲如沸萎胰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽技竟。三九已至冰肴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間榔组,已是汗流浹背熙尉。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留搓扯,地道東北人检痰。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像擅编,于是被迫代替她去往敵國和親攀细。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,675評論 2 359