Java 中 SerialVersionUID 关键字的重要性?\
javaobject oriented programmingprogramming更新于 2024/7/25 22:18:00
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