課程
/后端開發
/Java
/文件傳輸基礎——Java IO流
在代碼中s.defaultWriteObject();中size應該也被序列化了,為什么下邊還要再單獨序列化一次呢?
2017-06-04
源自:文件傳輸基礎——Java IO流 6-2
正在回答
這樣寫是出于兼容性考慮。
舊版本的JDK中,ArrayList的實現有所不同,會對length字段進行序列化。
而新版的JDK中,對優化了ArrayList的實現,不再序列化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流的使用,以及對象的序列化和反序列化的內容
5 回答為什么要序列化
5 回答為什么序列化和反序列化要分開進行?
2 回答什么是序列化和反序列化
5 回答序列化中子父類中父類為什么不用實現序列化而不報異常呢?
2 回答系列化與ArrayList的關系??
Copyright ? 2025 imooc.com All Rights Reserved | 京ICP備12003892號-11 京公網安備11010802030151號
購課補貼聯系客服咨詢優惠詳情
慕課網APP您的移動學習伙伴
掃描二維碼關注慕課網微信公眾號
2017-06-11
這樣寫是出于兼容性考慮。
舊版本的JDK中,ArrayList的實現有所不同,會對length字段進行序列化。
而新版的JDK中,對優化了ArrayList的實現,不再序列化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….