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.
youexecuted
java SerializationDemo
.Inresponse,youwouldobservethefol-
lowing output:
writeExternal() called
Employee() called
readExternal() called
John Doe
36