Java Reference
In-Depth Information
interface, and they must be declared private . If a class defines these methods, the
appropriate one is invoked by the ObjectOutputStream or ObjectInputStream
when an object is serialized or deserialized.
For example, a GUI component component might define a readObject() method
to give it an opportunity to recompute its preferred size upon deserialization. The
method might look like this:
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject(); // Deserialize the component in the usual way.
this.computePreferredSize(); // But then go recompute its size.
}
This method calls the defaultReadObject() method of the ObjectInputStream to
deserialize the object as normal and then takes care of the postprocessing it needs
to perform.
Example 9-2 is a more complete example of custom serialization. It shows a class
that implements a growable array of integers. This class defines a writeObject()
method to do some preprocessing before being serialized and a readObject()
method to do postprocessing after deserialization.
Example 9−2: IntList.java
package com.davidflanagan.examples.serialization;
import java.io.*;
/**
* A simple class that implements a growable array of ints, and knows
* how to serialize itself as efficiently as a non-growable array.
**/
public class IntList implements Serializable {
protected int[] data = new int[8]; // An array to store the numbers.
protected transient int size = 0; // Index of next unused element of array
/** Return an element of the array */
public int get(int index) throws ArrayIndexOutOfBoundsException {
if (index >= size) throw new ArrayIndexOutOfBoundsException(index);
else return data[index];
}
/** Add an int to the array, growing the array if necessary */
public void add(int x) {
if (data.length==size) resize(data.length*2); // Grow array if needed.
data[size++] = x;
// Store the int in it.
}
/** An internal method to change the allocated size of the array */
protected void resize(int newsize) {
int[] newdata = new int[newsize]; // Create a new array
System.arraycopy(data, 0, newdata, 0, size); // Copy array elements.
data = newdata;
// Replace old array
}
/** Get rid of unused array elements before serializing the array */
private void writeObject(ObjectOutputStream out) throws IOException {
if (data.length > size) resize(size); // Compact the array.
Search WWH ::




Custom Search