May 2004 Technical Tip – Object Persistence in Java
When a class is instantiated in a Java program, the resultant object is said to be volatile; that is, it will go away when the program ends. Object persistence is the process of saving an object to storage, and the simplest means of doing so is to use object serialization.
According to the API, "Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable."
So all that is necessary for a class to be serializable is to implement the Serializable interface, which has no methods. We will demonstrate the entire process here. We begin by creating a simple class called, appropriately, SimplePoint, which models an (x,y) point in the Cartesian plane.
Next, we create a simple application called WriteSimplePoint which instantiates a SimplePoint and writes that object to the C drive. Note the writeObject method of the ObjectOutputStream class can throw IOException (which I chose to throw back to the main method.)
Finally, we create a simple application called ReadSimplePoint which reads the object from the C drive. Note that the readObject method (1) can throw ClassNotFoundException and therefore requires a try/catch, and (2) returns an instance of Object which must then be cast to the desired class (SimplePoint in this case.)
The complete source for these examples can be found at http://www.caliberdt.com/tips. If you like concise but complete examples as shown in this article, then you’ll love our courses! We hope you’ll consider Caliber Data Training when you are looking for a Java training provider.