Presentation is loading. Please wait.

Presentation is loading. Please wait.

Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,

Similar presentations


Presentation on theme: "Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,"— Presentation transcript:

1 Advanced Java Class Serialization

2

3 Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it, and may later be used to re-create it Reasons to Serialize –Send them over a network connection including RMI, Sockets, etc. –Save to file

4 Pre-existing Serialization Functionality For primitives and Strings: –DataOutputStream and DataInputStream For other Objects: –ObjectOutputStream and ObjectInputStream –The object to be serialized must be an instance of the Serializable interface.

5 ObjectOutputStream and ObjectInputStream new ObjectOutputStream(OutputStream) new ObjectInputStream(InputStream) The arguments to the constructor can be any subclass of OutputStream / InputStream, and the Object Stream will send the serialized representation of the object along the stream that was passed into the constructor

6 Refusing Serialization To prevent an object from being serialized by the Output Streams, you can just not implement Serializable If you want to exclude one particular variable from Serialization, you may declare it transient. For runtime control of which fields are serialized, use –private static final ObjectStreamField[] serialPersistentFields =...;

7 Controlling Serialization Optional methods you can include in a class definition: (These are NOT in the Serializable interface.) –private void readObject (ObjectInputStream ois) throws ClassNotFoundException, IOException {...[must include a call to ois.defaultReadObject()]... } –private void writeObject (ObjectOutputStream oos) throws IOException {...[must include a call to oos.defaultWriteObject]... }

8 ObjectOutputStream details To send the Object over the stream more than once, you must call the reset method on the stream. You may set the version number of your class if you want: –to find the number: serialver class_name (at command line) –to set the number in the class: static final long serialVersionUID =...; If you don’t set it yourself, the JVM will set one automatically, but it may not change as often as you wish.

9 Your Serializer Project Must not use the Serializable interface Must not use ObjectInputStream Must not use ObjectOutputStream Must convert the Object to XML.


Download ppt "Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,"

Similar presentations


Ads by Google