transient 與 Java 序列化中的 final 如何協同工作?


在 Java 中,序列化是一種概念,我們可以使用它將物件的 state 寫入到位元組流中,以便我們可以透過網路傳輸(使用類似 JPA 和 RMI 的技術)。

Transient 變數 − Transient 變數的值永遠不會被考慮(它們從序列化流程中被排除)。也就是說,當我們宣告一個變數是 transient 時,在反序列化後它的值始終為 null、false 或零(預設值)。

因此,在對類的物件進行序列化時,如果你希望 JVM 忽略特定的例項變數,你需要將其宣告為 transient。

public transient int limit = 55; // will not persist
public int b; // will persist

示例

在以下 java 程式中,Student 類有兩個例項變數:name 和 age,其中 age 被宣告為 transient。在另一個名為 SerializeExample 的類中,我們嘗試對 Student 物件進行序列化和反序列化,並顯示它的例項變數。由於 age 是不可見的(transient),所以只顯示 name 值。

 線上演示

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable {
   private String name;
   private transient int age;
   public Student(String name, int age) {
      this.name = name;
      this.age = age;
   }
   public void display() {
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}
public class SerializeExample {
   public static void main(String args[]) throws Exception {
      //Creating a Student object
      Student std = new Student("Sarmista", 27);
      //Serializing the object
      FileOutputStream fos = new FileOutputStream("e:\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std);
      oos.close();
      fos.close();
      System.out.println("Values before de-serialization: ");
      std.display();
      System.out.println("Object serialized.......");
      //De-serializing the object
      FileInputStream fis = new FileInputStream("e:\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student deSerializedStd = (Student) ois.readObject();
      System.out.println("Object de-serialized.......");
      ois.close();
      fis.close();
      System.out.println("Values after de-serialization");
      deSerializedStd.display();
   }
}

輸出

Values before de-serialization:
Name: Sarmista
Age: 27
Object serialized.......
Object de-serialized.......
Values after de-serialization
Name: Sarmista
Age: 0

更新時間: 2019-10-15

862 次觀看

啟動你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.