java中static、transient修飾的屬性不能被序列化,statictransient
相關網頁:Java序列化的進階認識http://www.360doc.com/content/13/0728/18/13247663_303173972.shtml以下程式來自”http://bbs.csdn.net/topics/390155251“(已驗證)類Student1package test; import java.io.Serializable; public class Student1 implements Serializable{ private static final long serialVersionUID = 1L; private String name; private transient String password; private static int count = 0; public Student1(String name,String password){ System.out.println("調用Student的帶參構造方法 "); this.name = name; this.password = password; count++; } public String toString(){ return "人數:" + count + "姓名:" + name + "密碼:" + password; }} 類ObjectSerTest1 package test; import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream; public class ObjectSerTest1 { public static void main(String args[]){ try{ FileOutputStream fos = new FileOutputStream("test.obj"); ObjectOutputStream oos = new ObjectOutputStream(fos); Student1 s1 = new Student1("張三","123456"); Student1 s2 = new Student1("王五","56"); oos.writeObject(s1); oos.writeObject(s2); oos.close(); FileInputStream fis = new FileInputStream("test.obj"); ObjectInputStream ois = new ObjectInputStream(fis); Student1 s3 = (Student1) ois.readObject(); Student1 s4 = (Student1) ois.readObject(); System.out.println(s3); System.out.println(s4); ois.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } }}運行結果:調用Student的帶參構造方法 調用Student的帶參構造方法 人數:2姓名:張三密碼:null人數:2姓名:王五密碼:null 類Test1package test; import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream; public class Test1{ public static void main(String args[]){ try { FileInputStream fis = new FileInputStream("test.obj"); ObjectInputStream ois = new ObjectInputStream(fis); Student1 s3 = (Student1) ois.readObject(); Student1 s4 = (Student1) ois.readObject(); System.out.println(s3); System.out.println(s4); ois.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } } }運行結果:人數:0姓名:張三密碼:null人數:0姓名:王五密碼:null 類ObjectSerTest1 的運行結果顯示count=2,似乎被序列化了,但是類Test1的運行結果顯示count=0並未被序列化。”序列化儲存的是對象的狀態,靜態變數數以類的狀態,因此序列化並不儲存靜態變數。這裡的不能序列化的意思,是序列化資訊中不包含這個靜態成員域ObjectSerTest1 測試成功,是因為都在同一個機器(而且是同一個進程),因為這個jvm已經把count載入進來了,所以你擷取的是載入好的count,如果你是傳到另一台機器或者你關掉程式重寫寫個程式讀入test.obj,此時因為別的機器或新的進程是重新載入count的,所以count資訊就是初始時的資訊。“-----來自參考網頁重寫類Test1讀取test.obj顯示的結果是count的初始時的資訊,也驗證了上面一段話。最後,Java對象的static,transient 修飾的屬性不能被序列化。