Java Object Serialization


Object serialization is a form of I/O. It enables a program to read and write Java Objects to and from conventional Input Streams and Output Streams. Input and output streams, you will recall, can be associated with conventional files and with sockets. Thus, the same set of chained Java statements can read from and write to sockets or to files.

With conventional I/O classes and methods, the data that are read and written are primitive Java types. Object serialization extends this same flexibility to objects. Without Object Serialization, an object would have to manually read and write its variables individually. If a variable was not a primitive type but rather a class, it would have to write that object's variables, etc., recursively. Object serialization does something similarly, but automatically.

Object Serialization is often used in conjunction with Remote Method Invocation (RMI). RMI is similar to remote procedure calls. It allows a Java object running on one machine to invoke the methods of a Java object running on a different machine. If that remote object returns a a value that is an object, as many methods do, that object is returned to the calling program in the form of a serialized object.

The discussion of Object Serialization will include three steps. First, simple object variables are written to a file and read from the file. Next an object with several variables including one that is transient is written to a file and then read back in. The third program uses the same object as the second, but writes the object to a socket that has connected to a servlet and reads the object that is returned from the servlet.


Basic Object Serialization I/O

Simple String and Integer variables are written to a file and then read from that file. It illustrates the use of the ObjectOutputStream and ObjectInputStream classes. The program is written as an application.

Object Serialization with Complex Object

A more complex object that includes several variables is written to and read from a file.

Object Serialization to and from Servlet

In this example, three additional steps are illustrated. First, the object includes a transient variable that is not saved but restored when the object is read. Second, the readObject method is overridden. Third, the I/O takes place between a client applet and a servlet server using a socket.


References

References useful for this discussion include the following::