Java 序列化简介
Java 对象序列化是 JDK 1.1 中引入的一组开创性特性之一,用于作为一种将 Java 对象的状态转换为字节数组,以便存储或传输的机制,以后,仍可以将字节数组转换回 Java 对象原有的状态。
实际上,序列化的思想是 “冻结” 对象状态,传输对象状态(写到磁盘、通过网络传输等等),然后 “解冻” 状态,重新获得可用的 Java 对象。所有这些事情的发生有点像是魔术,这要归功于 ObjectInputStream/ObjectOutputStream 类、完全保真的元数据以及程序员愿意用Serializable 标识接口标记他们的类,从而 “参与” 这个过程。
显示一个实现 Serializable 的 Person 类。
package com.glut.demo;import java.io.Serializable;/** * 人类序列化 * @author qichunlin * */public class Person implements Serializable { private String firstName; private String lastName; private int age; private Person spouse; public Person(String fn, String ln, int a) { this.firstName = fn; this.lastName = ln; this.age = a; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public Person getSpouse() { return spouse; } public void setFirstName(String value) { firstName = value; } public void setLastName(String value) { lastName = value; } public void setAge(int value) { age = value; } public void setSpouse(Person value) { spouse = value; } public String toString() { return "[Person: firstName=" + firstName + " lastName=" + lastName + " age=" + age + " spouse=" + spouse.getFirstName() + "]"; }}
将 Person 序列化后,很容易将对象状态写到磁盘,然后重新读出它,下面的 JUnit 5 单元测试对此做了演示。
对Person进行反序列化
package com.glut.demo;import static org.junit.Assert.assertEquals;import static org.junit.Assert.fail;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class SerTest { @Test public void serializeToDisk() { try { Person ted = new Person("Ted", "Neward", 39); Person charl = new Person("Charlotte", "Neward", 38); ted.setSpouse(charl); charl.setSpouse(ted); FileOutputStream fos = new FileOutputStream("tempdata.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ted); oos.close(); } catch (Exception ex) { fail("Exception thrown during test: " + ex.toString()); } try { FileInputStream fis = new FileInputStream("tempdata.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Person ted = (Person) ois.readObject(); ois.close(); assertEquals(ted.getFirstName(), "Ted"); assertEquals(ted.getSpouse().getFirstName(), "Charlotte"); // Clean up the file new File("tempdata.ser").delete(); } catch (Exception ex) { fail("Exception thrown during test: " + ex.toString()); } }}