什么是 Java 序列化?有什么用?如何实现?(附示例代码)

什么是 Java 序列化?有什么用?如何实现?(附示例代码)

Java 序列化是将对象转换为字节序列的过程,以便在网络上传输或将对象保存到持久存储器中。反序列化则是将字节序列还原成对象的过程。Java 序列化可以将对象的状态保存到文件中,以便在下次运行程序时重新加载对象状态,这在某些场景下非常有用。

Java 序列化可以通过实现 Serializable 接口来实现,Serializable 是一个空接口,只要实现了 Serializable 接口的类就可以进行序列化和反序列化。在类上加上 Serializable 接口的实现后,就可以使用 ObjectOutputStream 和 ObjectInputStream 来实现对象的序列化和反序列化。

以下是一个示例代码,展示了如何将一个对象序列化并保存到文件中,以及如何从文件中读取并反序列化对象:

import java.io.*;

class Person implements Serializable {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

}

public class SerializationDemo {

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);

out.close();

fileOut.close();

System.out.println("Serialized data is saved in person.ser");

} catch (IOException e) {

e.printStackTrace();

}

try {

// 从文件中读取并反序列化对象

FileInputStream fileIn = new FileInputStream("person.ser");

ObjectInputStream in = new ObjectInputStream(fileIn);

Person newPerson = (Person) in.readObject();

in.close();

fileIn.close();

System.out.println("Deserialized data: " + newPerson.getName() + " " + newPerson.getAge());

} catch (IOException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

}

在上面的示例代码中,我们创建了一个 Person 类,并实现了 Serializable 接口。我们使用 ObjectOutputStream 将 Person 对象写入文件,并使用 ObjectInputStream 从文件中读取并反序列化 Person 对象。在反序列化时,需要将 Object 类型的对象强制转换为 Person 类型。