Java Reference
In-Depth Information
In the
readExternal()
method, you read the
name
and
gender
fields from the stream and set them in the
name
and
gender
instance variables.
Listing 7-27 and Listing 7-28 contain the serialization and deserialization logic for
PersonExt
objects. The output
of Listing 7-28 demonstrates that the value of the height field is the default value (
Double.NaN)
after you deserialize a
PersonExt
object.
Here are the steps to take to serialize and deserialize an object using
Externalizable
interface:
When you call the
•
writeObject()
method to write an
Externalizable
object, Java writes the
identity of the object to the output stream, and calls the
writeExternal()
method of its class.
You write the data related to the object to the output stream in the
writeExternal()
method.
You have full control over what object-related data you write to the stream in this method. If
you want to store some sensitive data, you may want to encrypt it before you write it to the
stream and decrypt the data when you read it from the stream.
•
When you call the
readObject()
method to read an
Externalizable
object, Java reads the
identity of the object from the stream. Note that for an
Externalizable
object, Java writes only
the object's identity to the output stream, not any details about its class definition. It uses the
object class's no-args constructor to create the object. This is the reason that you must provide
a no-args constructor for an
Externalizable
object. It calls the object's
readExternal()
method, so you can populate object's fields values.
Listing 7-27.
Serializing PersonExt Objects That Implement the Externalizable Interface
// PersonExtSerializationTest.java
package com.jdojo.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class PersonExtSerializationTest {
public static void main(String[] args) {
// Create three Person objects
PersonExt john = new PersonExt("John", "Male", 6.7);
PersonExt wally = new PersonExt("Wally", "Male", 5.7);
PersonExt katrina = new PersonExt("Katrina", "Female", 5.4);
// The output file
File fileObject = new File("personext.ser");
try (ObjectOutputStream oos = new ObjectOutputStream (
new FileOutputStream(fileObject))) {
// Write (or serialize) the objects to the object output stream
oos.writeObject(john);
oos.writeObject(wally);
oos.writeObject(katrina);
// Display the serialized objects on the standard output
System.out.println(john);
System.out.println(wally);
System.out.println(katrina);