Java Reference
In-Depth Information
An object of the
ObjectOutputStream
class is used to serialize an object. An object of the
ObjectInputStream
class is used to deserialize an object. You can also use objects of these classes to serialize values of the primitive data
types such as
int
,
double
,
boolean
, etc.
The
ObjectOutputStream
and
ObjectInputStream
classes are the concrete decorator classes for output and
input streams, respectively. However, they are not inherited from their abstract decorator classes. They are inherited
from their respective abstract component classes.
ObjectOutputStream
is inherited from
OutputStream
and
ObjectInputStream
is inherited from
InputStream
. This seems to be an inconsistency. However, this still fits into the
decorator pattern.
Your class must implement the
Serializable
or
Externalizable
interface to be serialized or deserialized. The
Serializable
interface is a marker interface. If you want the objects of a
Person
class to be serialized, you need to
declare the
Person
class as follows:
public class Person implements
Serializable
{
// Code for the Person class goes here
}
Java takes care of the details of reading/writing a
Serializable
object from/to a stream. You just need to pass the
object to write/read to/from a stream to one of the methods of the stream classes.
Implementing the
Externalizable
interface gives you more control in reading and writing objects from/to a
stream. It inherits the
Serializable
interface. It is declared as follows:
public interface Externalizable extends Serializable {
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
void writeExternal(ObjectOutput out) throws IOException;
}
Java calls the
readExternal()
method when you read an object from a stream. It calls the
writeExternal()
method when you write an object to a stream. You have to write the logic to read and write an object's fields inside the
readExternal()
and
writeExternal()
methods, respectively. Your class implementing the
Externalizable
interface
looks like the following:
public class Person implements Externalizable {
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// Write the logic to read the Person object fields from the stream
}
public void writeExternal(ObjectOutput out) throws IOException {
// Write the logic to write Person object fields to the stream
}
}
Serializing Objects
To serialize an object, you need to perform the following steps:
•
Have the references of the objects to be serialized.
•
Create an object output stream for the storage medium to which the objects will be written.
•
Write objects to the output stream.
•
Close the object output stream.