標籤: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關鍵字