Java 序列化是将对象的状态转换为字节流的过程,以便将其存储到文件或通过网络传输。反序列化则是将字节流还原为对象的过程。Java 序列化主要通过 java.io.Serializable
接口和 ObjectInputStream
、ObjectOutputStream
类实现。
以下是一个简单的 Java 序列化和反序列化的示例:
import java.io.*;
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Student{name='" + name + "', age=" + age + '}';
}
}
public class SerializationExample {
public static void main(String[] args) {
// 序列化对象
serializeObject();
// 反序列化对象
deserializeObject();
}
private static void serializeObject() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {
Student student = new Student("John", 25);
oos.writeObject(student);
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
private static void deserializeObject() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {
Student student = (Student) ois.readObject();
System.out.println("Object deserialized successfully: " + student);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在上述示例中,Student
类实现了 Serializable
接口,然后通过 ObjectOutputStream
对象将 Student
对象序列化到文件中,再通过 ObjectInputStream
对象将文件中的字节流反序列化为 Student
对象。这样,对象的状态就可以被持久化或在网络上传输。