課程
/后端開發(fā)
/Java
/文件傳輸基礎(chǔ)——Java IO流
在代碼中s.defaultWriteObject();中size應(yīng)該也被序列化了,為什么下邊還要再單獨(dú)序列化一次呢?
2017-06-04
源自:文件傳輸基礎(chǔ)——Java IO流 6-2
正在回答
這樣寫是出于兼容性考慮。
舊版本的JDK中,ArrayList的實現(xiàn)有所不同,會對length字段進(jìn)行序列化。
而新版的JDK中,對優(yōu)化了ArrayList的實現(xiàn),不再序列化length字段。
這個時候,如果去掉s.writeInt(size),那么新版本JDK序列化的對象,在舊版本中就無法正確讀取,
因為缺少了length字段。
因此這種寫法看起來多此一舉,實際上卻保證了兼容性。
附上官方解釋:defaultReadObject()?and?defaultWriteObject()?should?be?the?first?method?call?inside?readObject(ObjectInputStream?o)?and?writeObject(ObjectOutputStream?o).?It?reads?and?writes?all?the?non-transient?fields?of?the?class?respectively.?
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?i.e.?if?its?object?then?null?else?if?primitive?then?boolean?to?false,?int?to?0?etc….
舉報
為您介紹IO流的使用,以及對象的序列化和反序列化的內(nèi)容
5 回答為什么要序列化
5 回答為什么序列化和反序列化要分開進(jìn)行?
2 回答什么是序列化和反序列化
5 回答序列化中子父類中父類為什么不用實現(xiàn)序列化而不報異常呢?
2 回答系列化與ArrayList的關(guān)系??
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網(wǎng)安備11010802030151號
購課補(bǔ)貼聯(lián)系客服咨詢優(yōu)惠詳情
慕課網(wǎng)APP您的移動學(xué)習(xí)伙伴
掃描二維碼關(guān)注慕課網(wǎng)微信公眾號
2017-06-11
這樣寫是出于兼容性考慮。
舊版本的JDK中,ArrayList的實現(xiàn)有所不同,會對length字段進(jìn)行序列化。
而新版的JDK中,對優(yōu)化了ArrayList的實現(xiàn),不再序列化length字段。
這個時候,如果去掉s.writeInt(size),那么新版本JDK序列化的對象,在舊版本中就無法正確讀取,
因為缺少了length字段。
因此這種寫法看起來多此一舉,實際上卻保證了兼容性。
附上官方解釋:defaultReadObject()?and?defaultWriteObject()?should?be?the?first?method?call?inside?readObject(ObjectInputStream?o)?and?writeObject(ObjectOutputStream?o).?It?reads?and?writes?all?the?non-transient?fields?of?the?class?respectively.?
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?i.e.?if?its?object?then?null?else?if?primitive?then?boolean?to?false,?int?to?0?etc….