在Java中,序列化是一种将对象的状态(即其成员变量的值)转换为字节流的过程,以便于存储(例如保存到文件)或传输(例如通过网络发送)。要使用序列化,您需要遵循以下步骤:
Serializable
接口。这是一个标记接口,没有任何方法需要实现。实现此接口告诉Java虚拟机(JVM)该类的对象可以被序列化。import java.io.Serializable;
public class MyClass implements Serializable {
private int id;
private String name;
// 构造函数、getter和setter方法
}
ObjectOutputStream
对象,将对象写入到输出流中。序列化过程将自动处理对象内部的引用关系,确保整个对象图被正确地序列化。import java.io.*;
public class SerializeExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.setId(1);
obj.setName("MyObject");
try {
FileOutputStream fileOut = new FileOutputStream("myObject.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in myObject.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
ObjectInputStream
对象,从输入流中读取对象。反序列化过程将自动处理对象内部的引用关系,确保整个对象图被正确地恢复。import java.io.*;
public class DeserializeExample {
public static void main(String[] args) {
MyClass obj = null;
try {
FileInputStream fileIn = new FileInputStream("myObject.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
obj = (MyClass) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("MyClass class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized MyClass object...");
System.out.println("ID: " + obj.getId());
System.out.println("Name: " + obj.getName());
}
}
这样,您就可以使用Java序列化机制来保存和恢复对象了。请注意,序列化仅适用于具有可序列化成员变量的对象。如果对象包含不可序列化的成员变量(例如,文件句柄或网络连接),则需要将其声明为transient
,以便在序列化过程中忽略它们。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Java类方法怎样是序列化的