Java Reference
In-Depth Information
All code dealing with SQL and JDBC™ now is written. Remaining tasks for
the application are the creation of methods used to serialize and deserialize a
Password object.
Serializing an Object
Earlier, the Password class was modified to implement the Serializable
interface. It was necessary to modify the Password class so Password objects
could be serialized and deserialized; however, no methods were implemented.
As explained earlier, the Serializable interface simply is a marker interface, identi-
fying the object as a Serializable object. This allows an object to be serialized by
using the writeObject() method in the class, ObjectOutputStream, and deserial-
ized by using the readObject() method in the ObjectInputStream class. Classes
requiring exceptional handling during serialization and deserialization can
implement special methods with prescribed signatures to provide the needed
behavior. In many cases, however, the default behavior is sufficient to serialize
and deserialize an object.
The serializeObj() method serializes any Serializable object into a byte
array and then returns the byte array to the caller. Line 221 creates a new
ByteArrayOutputStream object. The ByteArrayOutputStream class implements
an output stream where data is written to a byte array. The size of the array
automatically increases as data is written to it. Data can be retrieved from the
array as a String or as a byte array, or it can be written to another output
stream. In line 222, the ByteArrayOutputStream object is used to create a new
ObjectOutputStream object which provides the writeObject() method, used
in line 224, to serialize the object passed as a parameter to the serializeObj()
method. In line 225, the flush() method is called to ensure that any buffered
output bytes are written through to the underlying ByteArrayOutputStream.
The close() method in line 226, comparable to the close() method in other
classes previously mentioned, closes the stream, releasing any associated
resources. Finally, the toByteArray() method of the ByteArrayOutputStream
object is called, creating a newly allocated byte array with the size and contents
of the output stream buffer and returning the contents as a byte array, which is
returned to the caller of the serializeObj() method.
The step on the next page enters code to serialize an object to a byte array.
Closing a ByteArrayOutputStream
Closing an ObjectOutputStream releases resources, but closing a
ByteArrayOutputStream has no effect. Interestingly enough, the
methods in the ByteArrayOutputStream class can be called after
the stream has been closed. This avoids the need for a byte array
to temporarily hold the returned value of the toByteArray()
method call.
Search WWH ::




Custom Search