Java序列化是指將Java對象裝換為二進制數據流,以便在網絡中傳輸、存儲或復制。實現序列化需要實現Serializable接口,常見的序列化方式包括Java原生序列化和第三方庫的序列化。
在Java的原生序列化中,使用ObjectOutputStream類將對象輸出為字節流,而使用ObjectInputStream類將字節流反序列化回對象。以下是一個Java原生序列化的示例:
import java.io.*; public class SerializationExample { public static void main(String[] args) throws IOException, ClassNotFoundException { FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); Employee employee = new Employee("Tom", "Manager", 10000); out.writeObject(employee); out.close(); fileOut.close(); FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Employee employee2 = (Employee) in.readObject(); in.close(); fileIn.close(); System.out.println("Name: " + employee2.name); System.out.println("Title: " + employee2.title); System.out.println("Salary: " + employee2.salary); } } class Employee implements Serializable { String name; String title; transient int salary; public Employee(String name, String title, int salary) { this.name = name; this.title = title; this.salary = salary; } }
除了Java原生序列化,還有一些第三方庫可以用來實現序列化,例如Google的Protocol Buffer和Apache的Avro。這些庫一般都使用更加高效的序列化算法,同時可以提供跨語言支持。