Java 中瞬態變數是什麼?說明。


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

在序列化一個類的物件時,如果你希望 JVM 忽略一個特定的例項變數,你可以在宣告該變數時使用 transient。

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

在以下 Java 程式中,Student 類有兩個例項變數 name 和 age,其中 age 被宣告為 transient。在另一個名為 EampleSerialize 的類中,我們嘗試序列化和反序列化 Student 物件並顯示其例項變數。由於 age 是不可見的(瞬態的),因此僅顯示 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 String getName() {
      return this.name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public int getAge() {
      return this.age;
   }
}
public class ExampleSerialize{
   public static void main(String args[]) throws Exception{
      Student std1 = new Student("Krishna", 30);
      FileOutputStream fos = new FileOutputStream("e:\student.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(std1);
      FileInputStream fis = new FileInputStream("e:\student.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      Student std2 = (Student) ois.readObject();
      System.out.println(std2.getName());
   }
}

輸出

Krishna

更新於:2019-07-30

319 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.