Java Reference
In-Depth Information
object (or an array element) refers to another object, writeObject() is again
invoked recursively. Thus, a single call to writeObject() may result in an entire
object graph being serialized. When two or more objects each refer to the other,
the serialization algorithm is careful to only output each object once; write-
Object() can't enter infinite recursion.
Deserializing an object simply follows the reverse of this process. An object is read
from a stream of data by calling the readObject() method of an ObjectInput-
Stream . This recreates the object in the state it was in when serialized. If the object
refers to other objects, they are recursively deserialized as well.
Example 9-1 demonstrates the basics of serialization. The example defines generic
methods that can store and retrieve any serializable object's state to and from a
file. It also includes an interesting deepclone() method that uses serialization to
copy an object graph. The example includes a Serializable inner class and a test
class that demonstrates the methods at work.
Example 9−1: Serializer.java
package com.davidflanagan.examples.serialization;
import java.io.*;
/**
* This class defines utility routines that use Java serialization.
**/
public class Serializer {
/**
* Serialize the object o (and any Serializable objects it refers to) and
* store its serialized state in File f.
**/
static void store(Serializable o, File f) throws IOException {
ObjectOutputStream out = // The class for serialization
new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(o);
// This method serializes an object graph
out.close();
}
/**
* Deserialize the contents of File f and return the resulting object
**/
static Object load(File f) throws IOException, ClassNotFoundException {
ObjectInputStream in = // The class for de-serialization
new ObjectInputStream(new FileInputStream(f));
return in.readObject();
// This method deserializes an object graph
}
/**
* Use object serialization to make a "deep clone" of the object o.
* This method serializes o and all objects it refers to, and then
* deserializes that graph of objects, which means that everything is
* copied. This differs from the clone() method of an object which is
* usually implemented to produce a "shallow" clone that copies references
* to other objects, instead of copying all referenced objects.
**/
static Object deepclone(final Serializable o)
throws IOException, ClassNotFoundException
{
// Create a connected pair of "piped" streams.
Search WWH ::




Custom Search