Java Reference
In-Depth Information
name = in.readUTF();
age = in.readInt();
}
@Override
public void writeExternal(ObjectOutput out) throws IOEx-
ception
{
System.out.println("writeExternal() called");
out.writeUTF(name);
out.writeInt(age);
}
}
Employee declaresa public Employee() constructorbecauseeachclassthat
participates in externalization must declare a public noargument constructor. The
deserialization mechanism calls this constructor to instantiate the object.
Caution The deserialization mechanism throws InvalidClassException
with a “no valid constructor” message when it doesn't detect a public noargument
constructor.
Initiate externalization by instantiating ObjectOutputStream and calling its
writeObject() method,orbyinstantiating ObjectInputStream andcallingits
readObject() method.
Note When passing an object whose class (directly/indirectly) implements Ex-
ternalizable to writeObject() ,the writeObject() -initiatedserialization
mechanism writes only the identity of the object's class to the object output stream.
Suppose you compiled Listing 8-15 ' s SerializationDemo.java source code
and Listing8-18 's Employee.java sourcecodeinthesamedirectory.Nowsuppose
youexecuted java SerializationDemo .Inresponse,youwouldobservethefol-
lowing output:
writeExternal() called
Employee() called
readExternal() called
John Doe
36
Search WWH ::




Custom Search