Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของ SerialVersionUID ใน Java Serialization


SerialVersionUID

  • SerialVersionUID ต้องประกาศเป็น private static final long คำนวณโดยคอมไพเลอร์จากสถานะคลาสและแอตทริบьюท ตัวเลขนี้ช่วยให้ JVM ระบุสถานะออบเจ็กต์เมื่ออ่านจากไฟล์
  • ใช้ระหว่าง deserialization เพื่อตรวจสอบว่า sender และ receiver ของ serialized object โหลดคลาสที่ compatible ว่าด้วย serialization หากต่างกันจะโยน InvalidClassException
  • หากไม่ระบุ serialVersionUID รันไทม์จะคำนวณ default 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