public class Person
implements java.io.Serializable
{
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; }
private String firstName;
private String lastName;
private int age;
private Person spouse;
}
将 Person 序列化后,很容易将对象状态写到磁盘,然后重新读出它,下面的 JUnit 4 单元测试对此做了演示。
清单 2. 对 Person 进行反序列化
public class SerTest
{
@Test public void serializeToDisk()
{
try
{
com.tedneward.Person ted = new com.tedneward.Person("Ted", "Neward", 39);
com.tedneward.Person charl = new com.tedneward.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);
com.tedneward.Person ted = (com.tedneward.Person) ois.readObject();
ois.close();