JAVA對象序列化(Serializable、ObjectOutputStream、ObjectInputStream、 transient)

來源:互聯網
上載者:User

標籤:tor   color   throws   傳輸   leo   進位   對象   public   ...   

1)對象序列化是把一個對象變為二進位的資料流的一種方法。對象序列化後可以方便的實現對象的傳輸或儲存。

2)如果一個類的對象想被序列化,則對象所在的類必須實現Serialilzable介面。此介面中沒有定義任何方法,所以此借口是一個標識介面,表示一個類具備被序列化的能力。

3)對象被序列化後變為二進位,可以經過位元據流進行傳輸。此時必須依靠對象輸出資料流(ObjectOutputStream)和對象輸入資料流(ObjectInputStream)。

4)在序列化中,只有屬性被序列化。因為每個對象都具有相同的方法,但是每個對象的屬性是不相同的,也就是說,對象儲存的只有屬性資訊,所以在序列化時,只有屬性被序列化。

 1 public class Person implements Serializable { 2     private String name; 3     private int age; 4     public Person(String name,int age){ 5         this.name = name; 6         this.age = age; 7     } 8     public String toString(){ 9         return this.name + "....." + this.age;10     }11 }
 1 import java.io.File; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.ObjectOutputStream; 6 import java.io.OutputStream; 7  8 public class SerDemo01 { 9     10     public static void main(String[] args) throws Exception {11         File f = new File("D:" + File.separator + "test.txt");12         ObjectOutputStream oos = null;13         OutputStream out = new FileOutputStream(f);14         oos = new ObjectOutputStream(out);15         oos.writeObject(new Person("zhangsan",30));16         oos.close();17     }18 19 }
 1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.InputStream; 4 import java.io.ObjectInputStream; 5  6 public class SerDemo02 { 7  8     public static void main(String[] args) throws Exception{ 9         File f = new File("D:" + File.separator + "test.txt");10         ObjectInputStream ois = null;11         InputStream input = new FileInputStream(f);12         ois = new ObjectInputStream(input);13         Object obj = ois.readObject();14         ois.close();15         System.out.println(obj);16     }17 18 }

輸出結果為:張三.....30

 

如果一個對象的某些屬性不希望被序列化,則可以使用transient關鍵字進行聲明,

如果將上述Person類中的private String name;修改為private transient String name;

最後輸出的結果為:null.....30

JAVA對象序列化(Serializable、ObjectOutputStream、ObjectInputStream、 transient)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.