20.2.Serialization
Saturday, April 17, 2010
Serialization
The Java Virtual Machine (JVM) supports the ability to read or write an object to a stream. This capability is called serialization, the process of "flattening" an object so that it can be saved to some permanent storage or passed to another object via the OutputStream class.
When writing an object , it is important that its state be written in a serialized form such that the object can be reconstructed as it is being read. Saving an object to some type of permanent storage is known as persistence.
The streams used for deserializing and serializing are the ObjectInputSt ream and theObjectOutputStream classes, respectively.
To allow an object to be serializable ( i.e., can be saved and retrieved) , its class should implement the Serializable interface.
The class should also provide a default constructor or a constructor with no arguments. One nice thing about serializability is that it is inherited, which means that we don’t have to implement Serializable on every class.
This means less work for programmers. You can just implement Serializable once along the class heirarchy.
The transient Keyword
When an object is serialized, only the object ’s data are preserved. Methods and constructors are not part of the serialized stream. There are some objects though that are not serializable because the data they represent constantly changes.
Some examples of such objects are FileInputStream and Thread objects. A NotSerializableException is thrown if the serialization operation fails for some reason.
A class containing a non-serializable object can still be serialized, if the reference to this non- serializable object is marked with the transient keyword.
Consider the following example:
The transient keyword prevents the data from being serialized. Instantiating objects from this class can now be written to an OutputSt ream.
Serialization: Writing an Object Stream
To write an object to a stream, you need to use the ObjectOutputStream class and its writeObject method.
The writeObject method has the following signature:
where obj is the object to be written to the stream.
The example below writes a Boolean object to an ObjectOutputStream.
The Boolean class implements the Serializable interface. Thus, objects instantiated from this class can be written to and read from a stream.
When you compile this program boolen.ser file will be formed in your local directory.
Deserialization: Reading an Object St ream
To read an object from a stream, you need to use the ObjectInputStream class and its
readObject method. The readObject method has the following signature:
where obj is the object to be read from the stream. The Object type returned should be typecasted to the appropriate class name before methods on that class can be executed.
The example below reads a Boolean object from an
ObjectInputStream. This is a continuation of the previous example on serialization.
The Java Virtual Machine (JVM) supports the ability to read or write an object to a stream. This capability is called serialization, the process of "flattening" an object so that it can be saved to some permanent storage or passed to another object via the OutputStream class.
When writing an object , it is important that its state be written in a serialized form such that the object can be reconstructed as it is being read. Saving an object to some type of permanent storage is known as persistence.
The streams used for deserializing and serializing are the ObjectInputSt ream and theObjectOutputStream classes, respectively.
To allow an object to be serializable ( i.e., can be saved and retrieved) , its class should implement the Serializable interface.
The class should also provide a default constructor or a constructor with no arguments. One nice thing about serializability is that it is inherited, which means that we don’t have to implement Serializable on every class.
This means less work for programmers. You can just implement Serializable once along the class heirarchy.
The transient Keyword
When an object is serialized, only the object ’s data are preserved. Methods and constructors are not part of the serialized stream. There are some objects though that are not serializable because the data they represent constantly changes.
Some examples of such objects are FileInputStream and Thread objects. A NotSerializableException is thrown if the serialization operation fails for some reason.
A class containing a non-serializable object can still be serialized, if the reference to this non- serializable object is marked with the transient keyword.
Consider the following example:
class MyClass implements Serializable { transient Thread thread; //try removing transient int data; /* some other data */ }
The transient keyword prevents the data from being serialized. Instantiating objects from this class can now be written to an OutputSt ream.
Serialization: Writing an Object Stream
To write an object to a stream, you need to use the ObjectOutputStream class and its writeObject method.
The writeObject method has the following signature:
public final void writeObject(Object obj) throws IOException
where obj is the object to be written to the stream.
The example below writes a Boolean object to an ObjectOutputStream.
The Boolean class implements the Serializable interface. Thus, objects instantiated from this class can be written to and read from a stream.
//ObjectOutputStream Example package serialization; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * * @author Administrator */ public class Main { /** * @param args the command line arguments */ Main() { Boolean booleanData = new Boolean("true"); try { FileOutputStream fos = new FileOutputStream("boolean.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(booleanData); oos.close(); } catch (IOException ie) { ie.printStackTrace(); } } public static void main(String[] args) { // TODO code application logic here Main ob = new Main(); } }
When you compile this program boolen.ser file will be formed in your local directory.
Deserialization: Reading an Object St ream
To read an object from a stream, you need to use the ObjectInputStream class and its
readObject method. The readObject method has the following signature:
public final Object readObject()throws IOException, ClassNotFoundException
where obj is the object to be read from the stream. The Object type returned should be typecasted to the appropriate class name before methods on that class can be executed.
The example below reads a Boolean object from an
ObjectInputStream. This is a continuation of the previous example on serialization.
//ObjectInputStream Example package serialization; import java.io.FileInputStream; import java.io.ObjectInputStream; /** * * @author Administrator */ public class Main { /** * @param args the command line arguments */ Main() { Boolean booleanData = null; try { FileInputStream fis = new FileInputStream("boolean.ser"); ObjectInputStream ois = new ObjectInputStream(fis); booleanData = (Boolean) ois.readObject(); ois.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Unserialized Boolean from " + "boolean.ser"); System.out.println("Boolean data: " + booleanData); System.out.println("Compare data with true: " + booleanData.equals(new Boolean("true"))); } public static void main(String[] args) { // TODO code application logic here Main ob = new Main(); } }
Labels:
Files and Streams