SerialVersionUID
- SerialVersionUID phải khai báo là biến private static final long. Số này được compiler tính dựa trên trạng thái lớp và thuộc tính. Giúp JVM xác định trạng thái đối tượng khi đọc từ file.
- SerialVersionUID dùng trong deserialization để xác minh sender và receiver của đối tượng serialized đã tải các lớp tương thích về serialization. Nếu khác nhau, ném InvalidClassException.
- Nếu serialVersionUID không chỉ định, runtime tính default serialVersionUID dựa trên các khía cạnh của lớp.
Ví dụ
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");
}
}
Kết quả
Employee Id is: 115 Employee Name is: Raja Employee Location is: Hyderabad Object Serialized