介绍
序列化(Serialization)是将对象的状态转换为可存储或传输的格式的过程。通过序列化,可以将对象保存到文件中、数据库中,或者通过网络传输到远程系统。相应地,反序列化(Deserialization)是将这种存储或传输的格式转换回对象的过程。
在 Java 中,序列化通常使用 java.io.Serializable 接口。实现了 Serializable 接口的类的对象可以被序列化。为了控制序列化过程中的一些细节,可以使用一些特殊的字段或方法,例如 serialVersionUID。
serialVersionUID 的作用
serialVersionUID 是一个唯一的版本标识符,用于确保在反序列化过程中,加载的类和序列化的对象是兼容的。如果类发生了变化(如新增或修改字段),可能会导致反序列化失败。如果没有显式定义 serialVersionUID,Java 会根据类的结构自动生成一个 ID,但这不是绝对可靠的。因此,建议显式定义 serialVersionUID。
示例
定义一个可序列化的类
import java.io.Serializable;public class Person implements Serializable {private static final long serialVersionUID = 1L;private String name;private int age;// 构造函数public Person(String name, int age) {this.name = name;this.age = age;}// Getter 和 Setter 方法public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{name='" + name + "', age=" + age + "}";}
}
序列化对象
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;public class SerializeExample {public static void main(String[] args) {Person person = new Person("Alice", 30);try (FileOutputStream fileOut = new FileOutputStream("person.ser");ObjectOutputStream out = new ObjectOutputStream(fileOut)) {out.writeObject(person);System.out.println("对象已序列化");} catch (IOException i) {i.printStackTrace();}}
}
反序列化对象
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ClassNotFoundException;public class DeserializeExample {public static void main(String[] args) {Person person = null;try (FileInputStream fileIn = new FileInputStream("person.ser");ObjectInputStream in = new ObjectInputStream(fileIn)) {person = (Person) in.readObject();System.out.println("对象已反序列化");System.out.println("Name: " + person.getName());System.out.println("Age: " + person.getAge());} catch (IOException i) {i.printStackTrace();} catch (ClassNotFoundException c) {System.out.println("Person 类未找到");c.printStackTrace();}}
}