21.2. Implementing the Serializable Interface
As I hope you still remember, the fundamental step in making objects serializable is to implement the Serializable interface in every class that defines objects you want written to a file. You need a methodical approach here, so how about top-down—starting with the SketchModel class.
Try It Out: Serializing SketchModel ObjectsThis is where you get a great deal from astonishingly little effort. To implement serialization for the SketchModel class you must first modify the class definition header to: class SketchModel extends Observable implements Iterable<Element>, Serializable { The Serializable interface is defined in the java.io package, so you need to add the following import statement to the beginning of the SketchModel.java file: import java.io.Serializable; The Serializable interface declares no methods—so that's it so far as the SketchModel class is concerned! Is that enough to serialize a sketch? Not quite. For a class to be serializable, all its data members must be serializable or declared as transient. If this is not the case, then an exception of type NotSerializableException will be thrown when you try to serialize an object. To avoid this you must trawl through the data elements of the SketchModel class, and if any of these are your own classes, you must make sure they either implement the Serializable interface or are declared as transient. You also cannot assume that objects of a standard class type are serializable ... |
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.