Java序列化是將一個Java對象轉換為字節流的過程,以便將其存儲在磁盤或通過網絡傳輸。Java反序列化是將字節流轉換回Java對象的過程。Java序列化和反序列化是常用的對象持久化技術。在分布式系統和緩存應用中,進行Java序列化和反序列化可以實現高效的對象傳輸和數據存儲。
//Java序列化 public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Tom"; e.address = "Shanghai"; e.ID = 123; e.salary = 8000; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.printf("Serialized data is saved in /tmp/employee.ser"); } catch (IOException i) { i.printStackTrace(); } } } //Java反序列化 public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); e = (Employee) in.readObject(); in.close(); fileIn.close(); } catch (IOException i) { i.printStackTrace(); return; } catch (ClassNotFoundException c) { System.out.println("Employee class not found"); c.printStackTrace(); return; } System.out.println("Deserialized Employee..."); System.out.println("Name: " + e.name); System.out.println("Address: " + e.address); System.out.println("ID: " + e.ID); System.out.println("Salary: " + e.salary); } } //Employee類實現了Serializable接口 import java.io.Serializable; public class Employee implements Serializable { public String name; public String address; public transient int ID; public int salary; }
在Java序列化和反序列化中,要注意以下幾點:
1. 類必須實現Serializable接口,否則無法序列化。
2. 數據成員為transient修飾的變量不會被序列化。
3. 在反序列化時,必須和序列化時使用相同的類加載器。
4. 序列化和反序列化的性能較差,盡量避免在高并發的場景中使用。