Java序列化是將Java對象轉(zhuǎn)換成字節(jié)序列的過程,該過程可以將對象保存到硬盤或網(wǎng)絡(luò)中,方便后續(xù)讀取和傳輸。Java反序列化是將字節(jié)序列還原成Java對象的過程,反序列化可以從文件或網(wǎng)絡(luò)中讀取數(shù)據(jù)并還原成Java對象。
// Java序列化示例代碼 public class Employee implements Serializable{ public String name; public String address; public transient int SSN; public int number; public void mailCheck(){ System.out.println("Mailing a check to " + name + " " + address); } } public class SerializeDemo { public static void main(String [] args) { Employee e = new Employee(); e.name = "Jack"; e.address = "Address123"; e.SSN = 123456; e.number = 101; try { FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(e); out.close(); fileOut.close(); System.out.println("Serialized data is saved in /tmp/employee.ser"); } catch (IOException i) { i.printStackTrace(); } } }
上述代碼中,Employee類實現(xiàn)了Serializable接口,表示該類可以序列化。在SerializeDemo類的main方法中,創(chuàng)建了一個Employee對象,并將該對象序列化保存到文件中。ObjectOutputStream類用于將對象轉(zhuǎn)換成字節(jié)流,并寫入到文件中。
// 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("SSN: " + e.SSN); System.out.println("Number: " + e.number); } }
上述代碼中,創(chuàng)建了一個Employee對象,并使用ObjectInputStream類將保存在文件中的字節(jié)流反序列化還原成Employee對象。在try-catch語句塊中可以處理異常,最后再輸出反序列化后的Employee對象,顯示該對象的各個屬性值。
Java序列化和反序列化是Java編程中常用的工具,在分布式系統(tǒng)和Web應(yīng)用程序中有廣泛的應(yīng)用。開發(fā)者應(yīng)該注意序列化和反序列化的性能和安全問題,同時避免在序列化過程中意外暴露敏感信息。