隨筆 - 3, 文章 - 152, 評論 - 17, 引用 - 0
          數據加載中……

          Serializable java序列化

          1、實現Serializable回導致發布的API難以更改,并且使得package-private和private 這兩個本來封裝的較好的咚咚也不能得到保障了 2、Serializable會為每個類生成一個序列號,生成依據是類名、類實現的接口名、 public和protected方法,所以只要你一不小心改了一個已經publish的API,并且沒有自 己定義一個long類型的叫做serialVersionUID的field,哪怕只是添加一個getXX,就會 讓你讀原來的序列化到文件中的東西讀不出來(不知道為什么要把方法名算進去?) 3、不用構造函數用Serializable就可以構造對象,看起來不大合理,這被稱為 extralinguistic mechanism,所以當實現Serializable時應該注意維持構造函數中所維 持的那些不變狀態 4、增加了發布新版本的類時的測試負擔 5、1.4版本后,JavaBeans的持久化采用基于XML的機制,不再需要Serializable 6、設計用來被繼承的類時,盡量不實現Serializable,用來被繼承的interface也不要 繼承Serializable。但是如果父類不實現Serializable接口,子類很難實現它,特別是 對于父類沒有可以訪問的不含參數的構造函數的時候。所以,一旦你決定不實現 Serializable接口并且類被用來繼承的時候記得提供一個無參數的構造函數 7、內部類還是不要實現Serializable好了,除非是static的,(偶也覺得內部類不適合 用來干這類活的) 8、使用一個自定義的序列化方法 看看下面這個保存一個雙向鏈表的例子:public class StringList implements Serializable{?private int size = 0;?private Entry head = null;??private static class Entry implements Serializable?{? String data;? Entry next;? Entry previous;?}?...//Remainder ommitted} 這樣會導致鏈表的每個元素以及元素之間的關系(雙向鏈表之間的連接)都保存下來,更好的方法是提供一個自定義的序列化如下: //String List with a resonable custom serialized formclass StringList implements Serializable{? private transient int size = 0;?????? //!transient? private transient Entry head = null;? //!transient? ? //no longer serializable!? private static class Entry? {??? String data;??? Entry next;??? Entry previous;? }? ? //Appends the specified string to the list? public void add(String s) {/*...*/};? ? /**?? * Serialize this StringList instance ?? * @author yuchifang?? * @serialData The size of the list (the number of strings * it contains) is emitted(int), in the proper sequence?? */? private void writeObject(ObjectOutputStream s) throws IOException? {??? s.defaultWriteObject();??? s.writeInt(size);??? //Write out all elements in the proper order??? for (Entry e = head; e != null; e = e.next)????? s.writeObject(e.data);? }? ? private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException? {??? int numElements = s.readInt();??? ??? //Read in all elements andd insert them in list??? for (int i = 0; i < numElements; i++)????? add((String)s.readObject());? }? //...remainder omitted} 9、不管你選擇什么序列化形式,聲明一個顯式的UID: private static final long serialVersionUID = randomLongValue; 10、不需要序列化的東西使用transient注掉它吧,別什么都留著 11、writeObject/readObject重載以完成更好的序列化 readResolve 與 writeReplace重載以完成更好的維護invariant controllers

          posted on 2005-10-18 15:07 閱讀(346) 評論(0)  編輯  收藏 所屬分類: J2se

          主站蜘蛛池模板: 贵港市| 湖北省| 金坛市| 济源市| 菏泽市| 马鞍山市| 贵定县| 蒙自县| 紫阳县| 三原县| 崇信县| 桦南县| 葵青区| 奇台县| 哈密市| 富顺县| 姜堰市| 新平| 临潭县| 宜宾县| 华容县| 新民市| 酉阳| 平果县| 榆树市| 宝兴县| 泗阳县| 定安县| 满城县| 临湘市| 宁陕县| 集贤县| 永州市| 麻阳| 枣庄市| 东乡县| 鹤庆县| 高台县| 和田市| 梁平县| 绵阳市|