關於Java中的transient關鍵字

來源:互聯網
上載者:User

標籤:row   還原序列化   stat   java   void   cto   類型   欄位   關鍵字   

Java中的transient關鍵字是在序列化時候用的,如果用transient修飾變數,那麼該變數不會被序列化。

下面的例子中建立了一個Student類,有三個成員變數:id,name,age。age欄位被transient修飾,當該類被序列化的時候,age欄位將不被序列化。

 1 import java.io.Serializable;   2 public class Student implements Serializable{   3  int id;   4  String name;   5  transient int age;//Now it will not be serialized   6  public Student(int id, String name,int age) {   7   this.id = id;   8   this.name = name;   9   this.age=age;  10  }  11 }  

來建立一個用序列化的類:

 1 import java.io.*;   2 class PersistExample{   3  public static void main(String args[])throws Exception{   4   Student s1 =new Student(211,"ravi",22);//creating object   5   //writing object into file   6   FileOutputStream f=new FileOutputStream("f.txt");   7   ObjectOutputStream out=new ObjectOutputStream(f);   8   out.writeObject(s1);   9   out.flush();  10   out.close();  11   f.close();  12   System.out.println("success");  13  }  14 }  
Output: success

再來建立一個還原序列化的類:

1 import java.io.*;  2 class DePersist{  3  public static void main(String args[])throws Exception{  4   ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));  5   Student s=(Student)in.readObject();  6   System.out.println(s.id+" "+s.name+" "+s.age);  7   in.close();  8  }  9 }  
Output:211 ravi 0

由此可見,Student的age欄位並未被序列化,其值為int類型的預設值:0.

關於Java中的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.