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

          Serializable java序列化

          1、實現(xiàn)Serializable回導致發(fā)布的API難以更改,并且使得package-private和private 這兩個本來封裝的較好的咚咚也不能得到保障了 2、Serializable會為每個類生成一個序列號,生成依據(jù)是類名、類實現(xiàn)的接口名、 public和protected方法,所以只要你一不小心改了一個已經(jīng)publish的API,并且沒有自 己定義一個long類型的叫做serialVersionUID的field,哪怕只是添加一個getXX,就會 讓你讀原來的序列化到文件中的東西讀不出來(不知道為什么要把方法名算進去?) 3、不用構造函數(shù)用Serializable就可以構造對象,看起來不大合理,這被稱為 extralinguistic mechanism,所以當實現(xiàn)Serializable時應該注意維持構造函數(shù)中所維 持的那些不變狀態(tài) 4、增加了發(fā)布新版本的類時的測試負擔 5、1.4版本后,JavaBeans的持久化采用基于XML的機制,不再需要Serializable 6、設計用來被繼承的類時,盡量不實現(xiàn)Serializable,用來被繼承的interface也不要 繼承Serializable。但是如果父類不實現(xiàn)Serializable接口,子類很難實現(xiàn)它,特別是 對于父類沒有可以訪問的不含參數(shù)的構造函數(shù)的時候。所以,一旦你決定不實現(xiàn) Serializable接口并且類被用來繼承的時候記得提供一個無參數(shù)的構造函數(shù) 7、內部類還是不要實現(xiàn)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

          主站蜘蛛池模板: 丹寨县| 新建县| 宁陕县| 乌拉特前旗| 广饶县| 通化县| 乡城县| 奎屯市| 临邑县| 大关县| 渭源县| 香河县| 方正县| 松溪县| 邵武市| 平原县| 康平县| 嘉义市| 镇沅| 泸西县| 商都县| 容城县| 广河县| 武穴市| 长治市| 白水县| 綦江县| 沁源县| 项城市| 巴里| 新营市| 甘泉县| 广灵县| 隆回县| 星座| 鹤岗市| 增城市| 工布江达县| 普陀区| 浙江省| 建平县|