Reading Serialized Data


ObjectInputStream in =    new ObjectInputStream(socket.getInputStream()); Object o = in.readObject();



Java enables object instances to be serialized and written either to a file or across a network. In this phrase, we show how you can read from a network socket an object that has been serialized. This phrase assumes that we've previously created a socket to the server with which we want to communicate. See the phrase "Contacting a Server" in this chapter for more details on creating the socket instance.

In this phrase, we call the getInputStream() method of the socket instance to get a reference to the socket's input stream. Using this, we can instantiate an ObjectInputStream instance. The ObjectInputStream class is used to deserialize primitive data and objects previously written using an ObjectOutputStream. We use the readObject() method of the ObjectInputStream to read an object from the stream. We could then cast the object to its expected type. For example, if we were reading a Date object from the stream, we would use the following line to read it:

Date aDate = (Date)in.readObject();


All data fields that are non-transient and non-static will be restored to the value they had when the object was serialized.

Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams. When implementing a serializable class it is strongly recommended that you declare a serialVersionUID data member. This field provides a version number that is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If you do not explicitly declare this field, a default serialVersionUID will be calculated for you. The default serialVersionUID is highly sensitive to all class details. You may make minor changes in a class and wish to keep the same version number as you consider it to still be compatible with the current version, therefore it is beneficial to declare your own serialVersionUID.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net