ObjectInputStream與ObjectOutputStream類所讀寫的對象必須實現Serializable接口,對象中的transient和static類型成員變量不會被讀取和寫入html
Serializable實際上是一個空接口java
package java.io; public interface Serializable { }
Serializable是一個空接口,沒有什麼具體內容,它的目的只是簡單的標識一個類的對象能夠被序列化。 什麼狀況下須要序列化網絡
a)當你想把的內存中的對象寫入到硬盤的時候;this
b)當你想用套接字在網絡上傳送對象的時候;htm
c)當你想經過RMI傳輸對象的時候; 再稍微解釋一下:a)好比說你的內存不夠用了,那計算機就要將內存裏面的一部分對象暫時的保存到硬盤中,等到要用的時候再讀入到內存中,硬盤的那部分存儲空間就是所謂的虛擬內存。在好比過你要將某個特定的對象保存到文件中,我隔幾天在把它拿出來用,那麼這時候就要實現Serializable接口;對象
public static void main(String args[]) throws Exception { class Student implements Serializable { private static final long serialVersionUID = 0xbc9903f7986df52fL; String name; int id ; int age; String department; public Student(String name, int id, int age, String department) { this.age = age; this.department = department; this.id = id; this.name = name; } } Student s1=new Student("張2三", 1, 5, "化學"); Student s2=new Student("李四1", 2, 9, "生物"); FileOutputStream fout = new FileOutputStream("C:\\student.txt"); ObjectOutputStream out=new ObjectOutputStream(fout); out.writeObject(s1); out.writeObject(s2); out.close(); FileInputStream fin=new FileInputStream("C:\\student.txt"); ObjectInputStream in=new ObjectInputStream(fin); try { s1=(Student) in.readObject(); s2=(Student) in.readObject(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } in.close(); System.out.print("name:"+s1.name); System.out.print(" id:"+s1.id); System.out.print(" age:"+s1.age); System.out.println(" department:"+s1.department); System.out.print("name:"+s2.name); System.out.print(" id:"+s2.id); System.out.print(" age:"+s2.age); System.out.println(" department:"+s2.department); }
上面就是一個序列化反序列化的例子blog
而後咱們考慮如下幾個問題接口
問題一:假設有A端和B端,若是2處的serialVersionUID不一致,會產生什麼錯誤呢?內存
問題二:假設2處serialVersionUID一致,若是A端增長一個字段,B端不變,會是什麼狀況呢?get
問題三:假設2處serialVersionUID一致,若是B段增長一個字段,A端不變,會是什麼狀況呢?
問題四:假設2處serialVersionUID一致,若是A端減小一個字段,B端不變,會是什麼狀況呢?
問題五:假設2處serialVersionUID一致,若是B端減小一個字段,A端不變,會是什麼狀況呢?