SE450: Serialization: Customization [12/32] Previous pageContentsNext page

Control over which refered objects are stored and how they are reconstructed.

Implement the Externalizable interface. This interface allows you to provide the methods writeExternal(ObjectOutput):void and readExternal(ObjectOutput).

You must provide a no-argument constructor as this is called when readExternal() is used to reconstruct objects.

file:Person2.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package serialization;
import java.io.*;

class Person2 implements Externalizable {
  private static final long serialVersionUID = 2008L;
  private String name = ""; private int age = 0;
  public Person2() { }
  public Person2(String name, int age) { this.name = name; this.age = age;}
  public String getName() { return name; }
  public int getAge() { return age; }
  public String toString() {return "Name: " + name + " Age: " + Integer.toString(age);}

  public void writeExternal(ObjectOutput out)
      throws IOException
  {
    out.writeObject(name);
    out.writeInt(age);
  }
  public void readExternal(ObjectInput in)
      throws IOException, ClassNotFoundException
  {
    name = (String) in.readObject();
    age = in.readInt();
  }
}

Previous pageContentsNext page