Java-序列化 —(二)

如果一個類不僅實現(xiàn)了Serializable接口碧浊,而且定義了 readObject(ObjectInputStream in)和 writeObject(ObjectOutputStream out)方法娱挨,那么將按照如下的方式進行序列化和反序列化:

ObjectOutputStream會調(diào)用這個類的writeObject方法進行序列化樟结,ObjectInputStream會調(diào)用相應(yīng)的readObject方法進行反序列化。

例:ArrayList集合類。其中elementData用transient修飾,不需要進行序列化。ArrayList自身實現(xiàn)了writeObject和readObject方法澎胡。

ArrayList源碼

    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException{
        // Write out element count, and any hidden stuff
        int expectedModCount = modCount;
        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }

        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

   private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA;

        // Read in size, and any hidden stuff
        s.defaultReadObject();

        // Read in capacity
        s.readInt(); // ignored

        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            int capacity = calculateCapacity(elementData, size);
            SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
            ensureCapacityInternal(size);

            Object[] a = elementData;
            // Read in all elements in the proper order.
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }

那么ObjectOutputStream又是如何知道一個類是否實現(xiàn)了writeObject方法呢?又是如何自動調(diào)用該類的writeObject方法呢娩鹉?
是通過反射機制實現(xiàn)的攻谁。

ObjectOutputStream的writeObject會根據(jù)傳進來的ArrayList對象得到Class,然后再包裝成 ObjectStreamClass底循,在writeSerialData方法里巢株,會調(diào)用ObjectStreamClass的 invokeWriteObject方法。

注意:s.defaultReadObject()函數(shù)在defaultReadObject()函數(shù)前執(zhí)行熙涤。
作用:
1阁苞、It reads and writes all the non transient fields of the class respectively.

2困檩、 These methods also helps in backward and future compatibility. If in future you add some non-transient field to the class and you are trying to deserialize it by the older version of class then the defaultReadObject() method will neglect the newly added field, similarly if you deserialize the old serialized object by the new version then the new non transient field will take default value from JVM

/**
 * FileName: ArrayListTest
 * Author:   Sandy
 * Date:     2018/12/1 14:25
 * Description:
 * Version: v1.0.0
 */

package AggregationDemo;

import java.io.*;
import java.util.ArrayList;

public class ArrayListTest {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

            ArrayList arrayList = new ArrayList();

            arrayList.add(1);
            arrayList.add("123");


            System.out.println("1. 原始對象:" + arrayList);

            //ArrayList序列化
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("ArrayListTest"));
            outputStream.writeObject(arrayList);

            //反序列化
            ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("ArrayListTest"));
            ArrayList arrayList_other = (ArrayList) inputStream.readObject();

            arrayList.add(123.312);
            arrayList_other.add("abc");

            System.out.println("2. 原始對象:" + arrayList);
            System.out.println("3. 拷貝對象:" + arrayList_other);
    }

}

輸出

1. 原始對象:[1, 123]
2. 原始對象:[1, 123, 123.312]
3. 拷貝對象:[1, 123, abc]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市那槽,隨后出現(xiàn)的幾起案子悼沿,更是在濱河造成了極大的恐慌,老刑警劉巖骚灸,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件糟趾,死亡現(xiàn)場離奇詭異,居然都是意外死亡甚牲,警方通過查閱死者的電腦和手機义郑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來丈钙,“玉大人非驮,你說我怎么就攤上這事〕猓” “怎么了劫笙?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵星岗,是天一觀的道長。 經(jīng)常有香客問我允华,道長敷矫,這世上最難降的妖魔是什么例获? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任汉额,我火速辦了婚禮,結(jié)果婚禮上蠕搜,老公的妹妹穿的比我還像新娘。我一直安慰自己轨蛤,他們只是感情好虫埂,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著缝呕,像睡著了一般。 火紅的嫁衣襯著肌膚如雪供常。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天麻裁,我揣著相機與錄音煎源,去河邊找鬼香缺。 笑死,一個胖子當(dāng)著我的面吹牛赫悄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播姑隅,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼倔撞,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鄙陡?” 一聲冷哼從身側(cè)響起躏啰,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤给僵,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后帝际,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡斑粱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年则北,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片冷冗。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡蒿辙,死狀恐怖滨巴,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情恭取,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站攒发,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏羔砾。R本人自食惡果不足惜偶妖,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一趾访、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧屿聋,春花似錦藏鹊、人聲如沸转锈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽变隔。三九已至蟹倾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間肌厨,已是汗流浹背豁陆。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工表鳍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留祥诽,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓胁镐,卻偏偏與公主長得像盯漂,于是被迫代替她去往敵國和親笨农。 傳聞我的和親對象是個殘疾皇子就缆,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360