- Home
- Objectives

- XyzWs Study Guides
- Study Guides
- Study Notes
- Resources

- Mock Exams
SCJP Study Guide:
API Contents
Printer-friendly version |
Mail this to a friend
Object Serialization
The key to writing an object is to represent its state in a serialized form sufficient to reconstruct the object as it is read. Thus reading and writing objects is a process called object serialization. Object serialization is essential to building all but the most transient applications. You can use object serialization in the following ways:
- Remote Method Invocation (RMI)--communication between objects via sockets
- Lightweight persistence--the archival of an object for use in a later invocation of the same program.
We need a byte-coded representation of objects that can be stored in a file external to Java programs, so that the file can be read later and the objects can be reconstructed. Serialization provides a mechanism for saving and restoring objects.
Serializing an object means to code it as an ordered series of bytes in such a way that it can be rebuilt (really a copy) from that byte stream. Deserialization generates a new live object graph out of the byte stream.
The serialization mechanism needs to store enough information so that the original object can be recreated including all objects to which it refers (the object graph). When reconstructing an object from a streamWhen an object is retrieved from a stream, it is validated to ensure that it can be rebuilt as the intended object. Validation may fail if the class definition of the object has changed. Because the deserialization process will create new instances of the objects. Comparisons based on the "==" operator may no longer be valid.
What is it saved:
- The class of the object.
- The class signature of the object.
-
Values of all non-
transientand non-staticmembers, including members that refer to other objects.
If a duplicate object occurs when traversing the graph of references, only ONE copy is saved, but references are coded so that the duplicate links can be restored.
You need to know about object serialization from two points of view. First, you need to know how to serialize objects by writing them to an ObjectOutputStream and reading them in again using an ObjectInputStream. Second, you will want to know how to write a class so that its instances can be serialized.
Serializing Objects
An object is serializable only if its class or its super class implements the EMPTY interface java.io.Serializable or the Externalizable interface.
Two stream classes in java.io, ObjectInputStream and
ObjectOutputStream
, allow the creation of streams for object serialization and methods that write
to and read from these streams.
Reconstructing an object from a stream requires that the object first be written to a stream. Writing objects to a stream is a straightforward process.Once you've written objects and primitive data types to a stream, you'll likely want to read them out again and reconstruct the objects. This is also straightforward. For example
class ScheduledItem implements Serializable {
private String name;
private Date date;
public ScheduledItem(String name, Date date) {
this.name = name; this.date = date;
}
public Date getDate() { return date;}
public String getName() {return name;}
public void setDate(Date date) {this.date = date;}
public void setName(String string) {name = string;}
}
public class SerializationSample {
public static void main(String[] args) {
try {
FileOutputStream out = new FileOutputStream("myCalendar.ser");
ObjectOutputStream oos = new ObjectOutputStream(out);
ScheduledItem item = new ScheduledItem("Weekly Meeting",
new Date(106,1,1,11,30));
oos.writeObject(item);
oos.flush();
FileInputStream in = new FileInputStream("myCalendar.ser");
ObjectInputStream ois = new ObjectInputStream(in);
item = (ScheduledItem)ois.readObject();
System.out.println("Name : " + item.getName());
System.out.println("Date : " + item.getDate());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
A class whose objects are to be saved must implement interface Serializable, with no methods, or the Externalizable interface, with two methods. Otherwise, runtime exception will be thrown. If we do not implements serializable interface for ScheduledItem, then we will get the exception as following:
java.io.NotSerializableException: ScheduledItem at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at SerializationSample.main(SerializationSample.java:39)
Normally, the serialization of instances of a class are handled by the defaultWriteObject
method of ObjectOutputStream and the deserialization of any
instance of the class with the defaultReadObject method in ObjectInputStream.
You don't have to write any methods.
In the above example, we used the writeObject and readObject methods. The ObjectOutputStream and ObjectInputStream also implement methods for writing and reading primitive data and Strings from the interfaces DataOutput and DataInput: such as writeChar(), readChar(), writeInt(), readInt(), writeDouble(), readDouble(), writeUTF(), readUTF() and so on.
Notes
-
An object is serializable only if its class or its superclass implements the
Serializableinterface. - An object is serializable (itself implements the Serializable interface) even if its superclass is not. However, the first superclass in the hierarchy of the serializable class, that does not implements Serializable interface, MUST have a no-arg constructor. If this is violated, readObject() will produce a java.io.InvalidClassException
- The no-arg contructor of every non-serializable superclass will run when an object is deserialized. However, the deserialized objects? constructor does not run when it is deserialized.
- The class must be visible at the point of serialization.
- All primitive types are serializable.
- Transient fields (with transient modifier) are NOT serialized, (i.e., not saved or restored). A class that implements Serializable must mark transient fields of classes that do not support serialization (e.g., a file stream).
- Static fields (with static modifier) are Not serialized.
- If member vairiables of a serializable object reference to a non-serializable object, the code will compile but a RumtimeException will be thrown.