0% found this document useful (0 votes)
36 views

Serialization

To make a class serializable: 1. Implement the Serializable interface 2. Ensure instance-level state is serialized properly 3. Ensure superclass state is serialized properly 4. Override equals() and hashCode()

Uploaded by

krishIndia
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Serialization

To make a class serializable: 1. Implement the Serializable interface 2. Ensure instance-level state is serialized properly 3. Ensure superclass state is serialized properly 4. Override equals() and hashCode()

Uploaded by

krishIndia
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 1

How to Make a Class Serializable

1. Implement the Serializableinterface.


2. Make sure that instance-level, locally defined state is serialized properly.
3. Make sure that superclass state is serialized properly.
4. Override equals( )and hashCode( ).

Using Serialization
Serialization is a mechanism built into the core Java libraries for writing a graph of objects into a
stream of data. This stream of data can then be programmatically manipulated, and a deep copy
of the objects can be made by reversing the process. This reversal is often called deserialization.

In particular, there are three main uses of serialization:

As a persistence mechanism
If the stream being used is FileOutputStream, then the data will automatically be
written to a file.
As a copy mechanism
If the stream being used is ByteArrayOutputStream, then the data will be written to a
byte array in memory. This byte array can then be used to create duplicates of the original
objects.
As a communication mechanism
If the stream being used comes from a socket, then the data will automatically be sent
over the wire to the receiving socket, at which point another program will decide what to
do.

If we have a serializable class, we can save it to a file or make a copy of it simply by changing
the way we use the output of the serialization mechanism.

To serialize an object, create an instance of ObjectOutputStream and call the


writeObject( )method; to read in a serialized object, create an instance of
ObjectInputStream and call the readObject( )object.

Serializing an object involves doing two things:

1) creating an ObjectOuptutStream and


2) Calling writeObject( )with a single "top-level" instance.

FileOutputStream ser = new FileOutputStream ("C:\\temp\\test");


ObjectOutputStream serializer = new ObjectOutputStream(ser);
serializer.writeObject(serializableObject);

You might also like