Download Object Serialization

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Advanced Programming 2004, based on LY Stefanus’s Slides
Object Serialization
Object serialization: the process of converting an
object into a stream of bytes.
slide 10.1
Advanced Programming 2004, based on LY Stefanus’s Slides
Where to use
• as the basis for transfering objects via cut-and-paste.
(Alternative: MIME type string, see page. 162 JiaN)
• to transfer objects between a client and a server for
remote method invocation (RMI).
• Pre-initialized java beans, persistent java beans
• Pre-initialized applets
• Save user preferences and application state – a serialized
object is an instant file format that works for any
application.
• GUI Builder Tools, saving complete hierarchy Component
hierarchy.
• OS, hibernate (e.g. Windows XP)
slide 10.2
Advanced Programming 2004, based on LY Stefanus’s Slides
Serialization
• Object serialization: the process of converting an object
into a stream of bytes.
writeObject()
• Object deserialization: the process of converting a stream
of bytes back into a copy of the original object.
readObject()
• An object of any class that implements the
java.io.Serializable interface can be saved and
restored from a stream of bytes.
• Special stream classes from the package java.io,
ObjectInputStream and ObjectOutputStream, are
used to serialize primitive types and objects.
• Subclasses of Serializable classes are also serializable.
slide 10.3
Advanced Programming 2004, based on LY Stefanus’s Slides
• java.io.Serializable is an example of marker interface.
Marker interface is an interface that is entirely empty. A
class can implement this interface simply by naming it in its
implements clause without having to implement any methods.
• We can check whether an object is an instance of the
interface using the instanceof operator, so this technique
is a useful way to provide additional information about an
object.
• Another example of marker interface is
java.lang.Cloneable.
slide 10.4
Advanced Programming 2004, based on LY Stefanus’s Slides
• The default serialization mechanism saves the value of an
object's nonstatic and nontransient member variables.
• When an object is serialized, any object references that it
contains are also serialized. The implication is that any
object we serialize must contain only references to other
Serializable objects. We can take control by marking
nonserializable members as transient or overriding the
default serialization mechanisms.
• The transient modifier can be applied to any instance
variable to indicate that its contents are not useful outside
of the current context and should never be saved or
serialized.
• See the examples: Save.java, Load.java
slide 10.5
Advanced Programming 2004, based on LY Stefanus’s Slides
Save.java
//Create a hashtable and write (serialize) it to a file called h.ser
//The Hashtable object is serializable because it implements
//the Serializable interface.
import java.io.*;
import java.util.*;
public class Save {
public static void main(String[] args) {
Hashtable h = new Hashtable();
h.put("harry", "Harry Potter");
h.put("satu", new Integer(1));
h.put("pi", new Double(Math.PI));
try {
FileOutputStream fos = new FileOutputStream("h.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(h);
} catch (Exception e) {
System.err.println(e);
}
}
}
slide 10.6
Advanced Programming 2004, based on LY Stefanus’s Slides
Load.java
//Read (deserialize) the hashtable from the h.ser file.
import java.io.*;
import java.util.*;
public class Load {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("h.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Hashtable h = (Hashtable) ois.readObject();
System.out.println(h.get("harry"));//print: Harry Potter
System.out.println(h.get("satu"));//print: 1
} catch (Exception e) {
System.err.println(e);
}
}
}
slide 10.7
Advanced Programming 2004, based on LY Stefanus’s Slides
Class Versioning
• When an object is serialized, some information about its
class must obviously be serialized with it, so that the
correct class file cab be loaded when the object is
deserialized.
• The information about the class is represented by the :
Java.io.ObjectStreamClass.
• It contains the fully qualified name of the class and a
version number.
Static final long serialVersionUID = 280432937854755317L;
• To compute an initial value use JDK: serialver
slide 10.8
Advanced Programming 2004, based on LY Stefanus’s Slides
Custom Serialization
• Example 9-2 (page 175 JiaN2)
// This example is from the book "Java in a Nutshell, Second Edition".
// Written by David Flanagan. Copyright (c) 1997 O'Reilly & Associates.
// You may distribute this source code for non-commercial purposes only.
// You may study, modify, and use this example for any purpose, as long as
// this notice is retained. Note that this example is provided "as is",
// WITHOUT WARRANTY of any kind either expressed or implied.
import java.io.*;
/** A simple class that implements a growable
array or ints, and knows
* how to serialize itself as efficiently as a
non-growable array. */
public class IntList implements Serializable
{
slide 10.9
Advanced Programming 2004, based on LY Stefanus’s Slides
private int[] nums = new int[8]; // An array to store the numbers.
private transient int size = 0; // Index of next unused element of nums[].
/** Return an element of the array */
public int elementAt(int index) throws ArrayIndexOutOfBoundsException {
if (index >= size) throw new ArrayIndexOutOfBoundsException(index);
else return nums[index];
}
/** Add an int to the array, growing the array if necessary */
public void add(int x) {
if (nums.length == size) resize(nums.length*2); // Grow array, if needed.
nums[size++] = x;
// Store the int in it.
}
slide 10.10
Advanced Programming 2004, based on LY Stefanus’s Slides
/** An internal method to change the allocated size of the array */
protected void resize(int newsize) {
int[] oldnums = nums;
nums = new int[newsize];
// Create a new array.
System.arraycopy(oldnums, 0, nums, 0, size); // Copy array elements.
}
/** Get rid of unused array elements before serializing the array */
private void writeObject(ObjectOutputStream out) throws IOException {
if (nums.length > size) resize(size); // Compact the array.
out.defaultWriteObject();
// Then write it out normally.
}
/** Compute the transient size field after deserializing the array */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
// Read the array normally.
size = nums.length;
// Restore the transient field.
}
}
slide 10.11
Advanced Programming 2004, based on LY Stefanus’s Slides
Serialized Applets
<APPLET OBJECT = ”MyApplet.ser”
WIDTH=400
HEIGHT=200>
</APPLET>
Use Appletviewer.
slide 10.12
Advanced Programming 2004, based on LY Stefanus’s Slides
slide 10.13
JavaBeans Persistence
• Java 1.4 introduces a new serialization mechanism intended
for use with JavaBeans.
• Java.io serialization works by saving the state of an object
as a sequence of bytes in binary format.
• Java.beans persistence works by saving the state of an
object or a bean as a sequence of calls to the public methods
defined by the class, in XML format.
• Since JavaBeans persistence is based on the public API
rather than on the internal state, its mechanism allows
interoperability between different implementations of the
same API, and is suitable for longer-term storage of
serialized objects.
Advanced Programming 2004, based on LY Stefanus’s Slides
slide 10.14
JavaBeans Persistence (cont.)
• A bean or other objects can be serialized with
java.beans.XMLEncoder and can be deserialized with
java.beans.XMLDecoder.
• These classes write to and read from specified streams, but
they are not stream classes themselves.
• See the examples: SaveXML.java, LoadXML.java
Advanced Programming 2004, based on LY Stefanus’s Slides
SaveXML.java
//Create a hashtable and write (serialize) it to a file called h.xml
import java.io.*;
import java.util.*;
import java.beans.*;
public class SaveXML {
public static void main(String[] args) {
Hashtable h = new Hashtable();
h.put("harry", "Harry Potter");
h.put("satu", new Integer(1));
h.put("pi", new Double(Math.PI));
try {
FileOutputStream fos = new FileOutputStream("h.xml");
XMLEncoder enc = new XMLEncoder(fos);
enc.writeObject(h);
enc.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
slide 10.15
Advanced Programming 2004, based on LY Stefanus’s Slides
slide 10.16
h.xml
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.4.2" class="java.beans.XMLDecoder">
<object class="java.util.Hashtable">
<void method="put">
<string>harry</string>
<string>Harry Potter</string>
</void>
<void method="put">
<string>pi</string>
<double>3.141592653589793</double>
</void>
<void method="put">
<string>satu</string>
<int>1</int>
</void>
</object>
</java>
Advanced Programming 2004, based on LY Stefanus’s Slides
slide 10.17
LoadXML.java
//Read (deserialize) the hashtable from the h.XML file.
import java.io.*;
import java.util.*;
import java.beans.*;
public class LoadXML {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("h.xml");
XMLDecoder dec = new XMLDecoder(fis);
Hashtable h = (Hashtable) dec.readObject();
System.out.println(h.get("harry"));//print: Harry Potter
System.out.println(h.get("satu"));//print: 1
} catch (Exception e) {
System.err.println(e);
}
}
}
Advanced Programming 2004, based on LY Stefanus’s Slides
Advanced Serialization: Externalizable
• Only the identity of the class of an Externalizable instance
is written in the serialization stream.
• It is the responsibility of the class to save and restore the
contents of its instances, and it must coordinate with its
superclasses to do so.
• Each object to be stored is tested for the Externalizable
interface.
• If the object supports Externalizable, the writeExternal
method is called. If the object does not support
Externalizable and does implement Serializable, the object
is saved using ObjectOutputStream.
slide 10.18
Advanced Programming 2004, based on LY Stefanus’s Slides
Externalizable
Here's the complete definition of the Externalizable interface
that extends Serializable:
package java.io;
public interface Externalizable extends Serializable {
public void writeExternal(ObjectOutput out) throws
IOException;
public void readExternal(ObjectInput in) throws
IOException, java.lang.ClassNotFoundException;
}
slide 10.19
Advanced Programming 2004, based on LY Stefanus’s Slides
slide 10.20
What holds for an Externalizable class?
• It must implement the java.io.Externalizable interface.
• It must implement a writeExternal method to save the state
of the object. Also, it must explicitly coordinate with its
supertype to save its state.
• It must implement a readExternal method to read the data
written by the writeExternal method from the stream and
restore the state of the object.
• It must explicitly coordinate with the supertype to restore
its state.
• If externally defined format is being written, the
writeExternal and readExternal methods are solely
responsible for that format.