Java中SerialVersionUID关键字的重要性?

SerialVersionUID

  • 在Java中,SerialVersionUID必须声明为私有的静态最终长变量。 此数字由编译器根据类的状态和类属性计算。 当JVM从文件中读取对象的状态时,该数字将帮助JVM识别对象的状态

  • 在反序列化期间可以使用SerialVersionUID来验证序列化对象的发送方和接收方是否为该对象加载了与w.r.t序列化兼容的类。如果反序列化对象与序列化不同,则它可以引发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