Java Reference
In-Depth Information
The following step enters code to serialize an object to a byte array.
To Serialize an Object
1. Enter lines 217 through 229 as shown in Figure 11-17 on page 712.
The serializeObj() method uses a ByteArrayOutputStream and an
ObjectOutputStream to serialize an object to a byte array (Figure 11-33).
writeObject()
method
flush
and close
ObjectStream
new
ObjectOutputStream
to byte array
returns
byte array
FIGURE 11-33
Deserializing an Object
Deserializing an object is the reverse process of serialization. An object that
has been serialized and saved to a byte array, for example, is deserialized by con-
verting the data in the byte array into a stream and then reading (deserializing)
the stream data into an object of the original type. This process is what the
deserializeObj() method follows.
Line 240 takes a non-null byte array and creates a ByteArrayInputStream
object, which then is used to create a new ObjectInputStream object. Line 242
uses the readObject() method to deserialize the data to an object of type Object.
Recall that the Object class is the parent, or root, class of the class hierarchy in
Java. All objects have this class as a superclass and, consequently, all objects are of
type Object. The deserializeObj() method returns the object, relying on the
caller to properly downcast to the expected class, which was done earlier in the
call to this method. If a null byte array was passed as a parameter, then a null
object reference is returned by this method.
The following step enters code to deserialize a byte array to an object.
 
Search WWH ::




Custom Search