在Java中,序列化(Serialization)是将对象转换为字节流的过程,而反序列化(Deserialization)是将字节流转换为对象的过程。序列化与反序列化主要用于对象的持久化存储或对象在网络中的传输。
Serializable
接口,这是一个标记接口,没有任何方法需要实现。import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
// Constructors, getters and setters
}
ObjectOutputStream
类来实现序列化,将对象写入输出流中。import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializationExample {
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("Object has been serialized");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ObjectInputStream
类来实现反序列化,从输入流中读取对象。import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializationExample {
public static void main(String[] args) {
try (FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
Person person = (Person) in.readObject();
System.out.println("Object has been deserialized");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static final long serialVersionUID
进行控制。InvalidClassException
异常,所以在进行序列化和反序列化时要谨慎处理版本兼容性问题。以上是序列化与反序列化的基础教程,希望能帮助你了解如何在Java中进行对象的持久化存储与传输。