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