SerialVersionUID 關鍵字在 Java 中的重要性?\n


SerialVersionUID

  • 在 Java 中,**SerialVersionUID **必須宣告為 **private static final long** 變數。此數字是編譯器根據類的狀態和類屬性計算的。此數字有助於 JVM 在從檔案中讀取物件的狀態時標識物件的狀態。
  • **SerialVersionUID **可以在 **反序列化**過程中使用,以驗證已序列化的物件的傳送方和接收方針對該物件載入了相容的類,與 **序列化**相關。如果反序列化物件與序列化不同,則可能會丟擲 **InvalidClassException**。
  • 如果未指定 **serialVersionUID **,則執行時將基於類的各個方面為該類計算 **預設的 serialVersionUID** 值。

範例

import java.io.*;
class Employee implements Serializable {
   private static final long serialVersionUID = 5462223600l;
   int empId;
   String name;
   String location;
   Employee(int empId, String name, String location) {
      this.empId = empId;
      this.name = name;
      this.location = location;
   }
   void empData() {
      System.out.println("Employee Id is: "+ empId);
      System.out.println("Employee Name is: "+ name);
      System.out.println("Employee Location is: "+ location);
   }
}
public class EmployeeTest {
   public static void main(String[] args)throws Exception{
      Employee emp = new Employee(115, "Raja", "Hyderabad");
      emp.empData();
      FileOutputStream fos = new FileOutputStream("E:\Employee.txt");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(emp);
      System.out.println("Object Serialized");
   }
}

輸出

Employee Id is: 115
Employee Name is: Raja
Employee Location is: Hyderabad
Object Serialized


更新於: 02-Jul-2020

6K+ 瀏覽

開啟您的 職業

完成課程獲取認證

開始
廣告
© . All rights reserved.