Java Reference
In-Depth Information
Serializable is a Java interface without any method declarations. Simply
adding implements Serializable makes the objects of that class able to be serial-
ized—almost. Serialization does require that all of the attributes or data elements of
the class also be serializable. This stands to reason: Java cannot serialize the object
if it cannot serialize all the components of the class. Almost all the Java API classes
are already serializable, and all Java primitives are serializable. Unless MyClass con-
tains classes you have defined that are not serializable, it can be serialized.
Serialization is extremely powerful. Not only is the object itself serialized, but
all of the objects it contains are serialized. This continues in an iterative fashion un-
less some of the lowest levels of the data structure are serialized. The same applies
also to the objects contained in one of the Java Collections classes that will be dis-
cussed in more detail in the next chapter
Occasionally, you may have a reason not to serialize a data element in a class.
Suppose you have a large array of data that you use as a work area during process-
ing. You may have no need to save the data. Perhaps the data can be easily recreated
or has significance only during certain processes. You would not want to write the
data to disk or transmit it over the network. The transient keyword allows you to
specify that a data element (primitive, array, or object) should not be serialized.
public class MyClass
{
transient String [] myBigArray;
// code
}
To accomplish serialization, you need to use ObjectInputStream and Object-
OutputStream .
int i = 55;
String myValue = "some string data";
MyClass appData = new MyClass();
// Create the output streams.
FileOutputStream ostream = new FileOutputStream ("save.dat");
ObjectOutputStream oostream= new ObjectInputStream(ostream);
// Serialize the data.
oostream.writeInt(i);
oostream.writeObject(myValue);
oostream.writeObject(appData);
// Close the streams.
oostream.close();
ostream.close();
// Create the input streams.
Search WWH ::




Custom Search