Object serialization can be done at several different levels, ranging from simplie I/O of Java objects, to I/O of selective variables, to custom programmer control of I/O as might be done using proprietary formats. The basic steps for some of these options are outlined below.
Key classes include ObjectOutputStream and ObjectInputStream.
1. implements Serializable
Any program that wishes to use Java's standard Object I/O facilities must implement this marker interface. The Serializable interface includes no methods; it merely signals or enables this feature of the language.
Example:
public class BasicObjectIO implements Serializable {
2. ObjectOutputStream / ObjectInputStream
Create instances of ObjectOutputStream and ObjectInputStream to support writing and reading of objects to and from conventional I/O resources, such as files and sockets.
Example:
FileOutputStream fos = new FileOutputStream ( "testFile.dat" );
ObjectOutputStream oos = new ObjectOutputStream ( fos );
3. writeObject / readObject
Use the writeObject and readObject methods of ObjectOutputStream and ObjectInputStream to write and read objects.
Example:
oos.writeObject ( dataObject );
4. transient variables
For object variables that you do not wish to be written or read as part of a conventional writeObject or readObject, declaree them with the transient attribute.
Example:
private transient Date date;
In this example, date would not be written out as part of the object. thus, when the object is read in, date would have to recreated at that time.
5. private void readObject
The programmer can provide specialized object I/O and thereby, for example, restore transient variables, by including a readObject method in the class to be serialized. It must conform exactly to the form shown in the example below. Note its use of the defaultReadObject method for performing actual object I/O..
Example:
private void readObject ( ObjectInputStream in ) throws IOException, ClassNotFoundException {
in.defaultReadObject ();
timeMillis = System.currentTimeMillis ();
date = new Date ( timeMillis );
} // end readObject