Java Reference
In-Depth Information
S ERIALIZATION
Java provides an ability to transform any object into a stream of bytes and save the
stream of bytes to the file system, thus making the object persistent. Then, at a later
time, a program could read back the byte stream and transform the stream of bytes
back into an object. You can think of this mechanism as somewhat like teleporta-
tion in science fiction. You create an object in a VM, set various values in it, trans-
form it into bytes, and send it someplace else. Upon arrival at the other location,
another VM reassembles the bytes back into the original object with all of the val-
ues properly initialized to their “teleported” values.
The two VMs may be two actual VMs communicating in real time over a net-
work. Serialization is a key mechanism that lies behind Remote Method Invocation
(RMI). RMI permits a program running in one VM to invoke a method in a pro-
gram running on a different VM, one perhaps a continent away accessed through
a network.
The two VMs may be two executions of the VM on the same physical machine.
The serialization, in this case, may be to a file system. A program executes and ac-
cepts data from a user. The user decides to exit the program. The program saves the
data entered by the user to disk by serializing the Java objects that contain the data.
Later the user starts the program, and the program reads the saved data from disk,
serializes it back into the original objects, and the program can pick up where it left
off in interacting with the user.
Although you might think serialization would be difficult for you as a pro-
grammer to implement, it is actually quite simple. To make any class serializable
only requires that you add the Serializable interface tag to the class. In other
words, if you have a class defined like this:
public class MyClass
{
// code
}
About the only thing required to make the class serializable is to do this:
public class MyClass implements Serializable
{
// code
}
Search WWH ::




Custom Search