CS 596 Java Programming Fall Semester, 1998 Serialization |
||
---|---|---|
© 1998, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 21-Dec-98 |
Serialization
Serialization allows objects to be converted to a sequence of bytes
The sequence of bytes can be stored in a file, database, sent to a remote machine etc.
The sequence of bytes can be used to recreate the original object
Serializing
Making an Object Serializable
The object's class must implement the interface
import java.io.Serializable; class Roger implements Serializable { public int lowBid; public Roger(int lowBid ) { this.lowBid = lowBid; } public String toString() { return " " + lowBid; } }
Serializing and Deserializing Objects
The writeObject method of ObjectOutputStream serializes objects
The readObject method of ObjectInputStream deserializes objects
Example import java.io.*;
class SerializeDeserialize { public static void main( String args[] ) throws IOException { serialize(); deserialize(); } public static void serialize() throws Exception { OutputStream outputFile = new FileOutputStream( "Serialized" ); ObjectOutputStream cout = new ObjectOutputStream( outputFile ); cout.writeObject( new Roger( 1)); cout.close(); } public static void deserialize() throws Exception { InputStream inputFile = new FileInputStream( "Serialized" ); ObjectInputStream cin = new ObjectInputStream( inputFile ); System.out.println( cin.readObject() ); } }Output 1
ObjectOutputStream
Methods
annotateClass(Class)
writeByte(int)
close()
writeBytes(String)
defaultWriteObject()
writeChar(int)
drain()
writeChars(String)
enableReplaceObject(boolean)
writeDouble(double)
flush()
writeFloat(float)
replaceObject(Object)
writeInt(int)
reset()
writeLong(long)
write(byte[])
writeObject(Object)
write(byte[], int, int)
writeShort(int)
write(int)
writeStreamHeader()
writeBoolean(boolean)
writeUTF(String)
public final void writeObject(Object obj) throws IOException
Throws: InvalidClassException
ObjectInputStream
Methods
available()
readInt()
close()
readLine()
defaultReadObject()
readLong()
enableResolveObject(boolean)
readObject()
read()
readShort()
read(byte[], int, int)
readStreamHeader()
readBoolean()
readUnsignedByte()
readByte()
readUnsignedShort()
readChar()
readUTF()
readDouble()
registerValidation(ObjectInputValidation, int)
readFloat()
resolveClass(ObjectStreamClass)
readFully(byte[])
resolveObject(Object)
readFully(byte[], int, int)
skipBytes(int)
public final Object readObject() throws OptionalDataException, ClassNotFoundException, IOException
Throws: ClassNotFoundException
Serializable objects can contain other objects
import java.io.Serializable; import java.util.Vector; class Roger implements Serializable { public int lowBid; public int[] allBids = new int[10]; public Vector bidderNames = new Vector(); public Roger(int lowBid ) { this.lowBid = lowBid; bidderNames.addElement( "Bill"); } public String toString() { return " " + lowBid + " " + bidderNames; } }
Multiple Items on One Stream
If more than one object of the same type is put on the stream, the header information for the class is sent only once.
import java.io.*; class MultipleItems { public static void main( String args[] ) throws Exception { serialize(); deserialize(); } public static void serialize() throws IOException { OutputStream outputFile = new FileOutputStream( "Serialized" ); ObjectOutputStream cout = new ObjectOutputStream( outputFile ); cout.writeObject( new Roger( 2 )); cout.writeUTF( "Hi Mom" ); cout.writeObject( "Hi Dad" ); cout.writeFloat( 2.345F ); cout.writeObject( new Roger( 3 )); cout.close(); }
//Multiple Items - Continued
public static void deserialize() throws Exception { InputStream inputFile = new FileInputStream( "Serialized" ); ObjectInputStream cin = new ObjectInputStream( inputFile ); System.out.println( cin.readObject() ); System.out.println( cin.readUTF() ); System.out.println( cin.readObject() ); System.out.println( cin.readFloat() ); System.out.println( cin.readObject() ); } }Output 2 [Bill]
Hi Mom
Hi Dad
2.345
3 [Bill]
Saving and Recovering - A Simple Example
import java.io.*; import java.util.*; // Cheap demo class for something to save public class Student implements Serializable { String name; String address; public Student( String name, String address ) { this.name = name; this.address = address; } public String toString() { return name + "@" + address + "\n"; } }
//Saving and Recovering - A Simple Example public class StudentList implements Serializable { Vector list = new Vector(); String storageFileName; public StudentList( String fileForStorage) { storageFileName = fileForStorage; } public void addStudent( Student addToList ) { list.addElement( addToList ); } public String toString() { return list.toString(); } // Have the list save itself in a file public void save() throws IOException { OutputStream outputFile = new FileOutputStream( storageFileName ); ObjectOutputStream cout = new ObjectOutputStream( outputFile ); cout.writeObject( this ); cout.close(); }
//Saving and Recovering - A Simple Example //StudentList continued
// Recover a StudentList from a file public static StudentList fromFile( String studentListFile) throws OptionalDataException, ClassNotFoundException, IOException { InputStream inputFile = new FileInputStream( studentListFile ); ObjectInputStream cin = new ObjectInputStream( inputFile ); StudentList recoveredList = (StudentList) cin.readObject(); cin.close(); return recoveredList; } }
//Saving and Recovering - A Simple Example The driver program and Sample output
class Test public static void main( String args) throws Exception { StudentList cs535 = new StudentList( "cs535File"); cs535.addStudent( new Student( "Roger", "whitney@rohan")); cs535.addStudent( new Student( "Sam", "masc1232@rohan")); cs535.addStudent( new Student( "Ngu", "masc1111@rohan")); cs535.addStudent( new Student( "catMan", "masc43221@rohan")); System.out.println( cs535); cs535.save(); StudentList recoveredClass = StudentList.fromFile( "cs535File" ); System.out.println( recoveredClass); } }Output [Roger@whitney@rohan
, Sam@masc1232@rohan
, Ngu@masc1111@rohan
, catMan@masc43221@rohan
]
[Roger@whitney@rohan
, Sam@masc1232@rohan
, Ngu@masc1111@rohan
, catMan@masc43221@rohan
]
Non-Serializable Objects
Some objects should not be serialized
transient Example import java.io.Serializable; import java.util.Vector; class Roger implements Serializable { private int lowBid; private transient float averageBid; private int highBid; public Roger(int lowBid, int highBid ) { this.lowBid = lowBid; this.highBid = highBid; averageBid = (lowBid + highBid) /2; } public String toString() { return " " + lowBid + " " + averageBid; } }
// transient Example - Continued
class TransientExample { public static void main( String args[] ) throws Exception { serialize(); deserialize(); } public static void serialize() throws IOException { OutputStream outputFile = new FileOutputStream( "Serialized" ); ObjectOutputStream cout = new ObjectOutputStream( outputFile ); cout.writeObject( new Roger( 1, 5 )); cout.close(); } public static void deserialize() throws Exception { InputStream inputFile = new FileInputStream( "Serialized" ); ObjectInputStream cin = new ObjectInputStream( inputFile ); System.out.println( cin.readObject() ); } }Output 1 0.0
Customizing Deserialization
The readObject() method allows you to customize the deserialization of an object
The readObject() must have the signature given below
readObject must be implemented in the class of the object to be deserialized
private void readObject( ObjectInputStream in) { // this is normally called first in.defaultReadObject(); //Now you do the custom work }
defaultReadObject() throws the following exceptions
Throws: ClassNotFoundException
Example of readObject
import java.io.Serializable; import java.io.ObjectInputStream; import java.io.IOException; class Roger implements Serializable { private int lowBid; private transient float averageBid; private int highBid; public Roger(int lowBid, int highBid ) { this.lowBid = lowBid; this.highBid = highBid; averageBid = (lowBid + highBid)/2; } private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); averageBid = (lowBid + highBid)/2; } public String toString() { return " " + lowBid + " " + averageBid; } }
// Example of readObject - Continued
class ReadObjectExample { public static void main( String args[] ) throws Exception { serialize(); deserialize(); } public static void serialize() throws IOException { OutputStream outputFile = new FileOutputStream( "Serialized" ); ObjectOutputStream cout = new ObjectOutputStream( outputFile ); cout.writeObject( new Roger( 1, 5 )); cout.close(); } public static void deserialize() throws Exception { InputStream inputFile = new FileInputStream( "Serialized" ); ObjectInputStream cin = new ObjectInputStream( inputFile ); System.out.println( cin.readObject() ); } }Output 1 3.0
Customizing Serialization
The writeObject() method allows you to customize the serialization of an object
The writeObject() must have the signature given below
writeObject must be implemented in the class of the object to be deserialized
private void writeObject( ObjectOutputStream out ) { // normally do the custom work before // you call defaultWriteObject() out.defaultWriteObject(); }
defaultWriteObject() throws the following exceptions
Throws: IOException
Taking Complete Control
class Roger implements Serializable { private int lowBid; private float averageBid; private int highBid; public Roger(int lowBid, int highBid ) { this.lowBid = lowBid; this.highBid = highBid; averageBid = (lowBid + highBid)/2; } private void readObject( ObjectInputStream in) throws IOException { lowBid = in.readInt(); averageBid = in.readFloat(); highBid = in.readInt(); } private void writeObject( ObjectOutputStream out) throws IOException { out.writeInt( lowBid ); out.writeFloat( averageBid ); out.writeInt( highBid ); } public String toString() { return " " + lowBid + " " + averageBid; } }
Class Versions
The Problem
Start with a class:
class Unstable { double hereToday; }
Serialize an Unstable object to a file for later use
Now change the class
class Unstable { char goneTomorrow; }
After the class has changed, try to deserialize the object!
What should happen?
What could happen? (Hint nothing very good)
Class serialVersionUID
Java generates a serialVersionUID for each class
When deserializing an object, the serialVersionUID of the deserialized object and it class are checked
If they do not agree, an exception is thrown
Information Used to Compute the serialVersionUID
1. Class name
2. The class modifiers
3. The name of each interface
4. For each field of the class(except private static and private transient fields):
Controlling The Class Version
By declaring in your class a field of type and name
class Sam implements Serializable { private int lowBid; public Sam(int lowBid) { this.lowBid = lowBid; } }
Example of serialVersionUID
Start with this class:
class Roger implements Serializable { static final long serialVersionUID = 1L; private int lowBid; public Roger(int lowBid ) { this.lowBid = lowBid; } }
Serialize it with the following program. The rest of the example will read this serialized version of the Roger object
class SerializeRoger { public static void main( String args[] ) throws Exception { OutputStream outputFile = new FileOutputStream( "Serialized" ); ObjectOutputStream cout = new ObjectOutputStream( outputFile ); cout.writeObject( new Roger( 1, 5 )); cout.close(); } }
Example of serialVersionUID - Continued Change the class as follows and recompile
class Roger implements Serializable { static final long serialVersionUID = 1L; private int lowBid; public Roger(int lowBid ) { this.lowBid = lowBid; } public String toString() { return " " + lowBid + " " + averageBid; } }
Now deserialize the original Roger object with the program. There is no problem as the class has not changed any data
class ReadRogerObejct { public static void main( String args[] ) throws Exception { InputStream inputFile = new FileInputStream( "Serialized" ); ObjectInputStream cin = new ObjectInputStream( inputFile ); System.out.println( cin.readObject() ); } }
Example of serialVersionUID - Continued Now we add some new fields to the class. Since they are not in the saved Roger object, we add the readObject method to make some reasonable values for the new fields. Compiling the class and deserialize in the original Roger object with the ReadRogerObejct class. It will work.
class Roger implements Serializable { static final long serialVersionUID = 1L; private int lowBid; private transient float averageBid; private int highBid; public Roger(int lowBid, int highBid ) { this.lowBid = lowBid; this.highBid = highBid; averageBid = (lowBid + highBid)/2; } private void readObject( ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if ( highBid == 0) highBid = lowBid; averageBid = (lowBid + highBid)/2; } public String toString() { return " " + lowBid + " " + averageBid; } }
Example of serialVersionUID - Continued We can change the class to the following and it will still work to deserialize the original Roger object. Note that the field "lowBid" is not in this class.
class Roger implements Serializable { static final long serialVersionUID = 1L; private int highBid; public Roger(int highBid) { this.highBid= highBid; } }
Example of serialVersionUID - Continued ¿So what does not work?
This is actually two questions:
class Roger implements Serializable { static final long serialVersionUID = 1L; private float lowBid; public Roger(int lowBid) { this.lowBid = lowBid; } }
Serialver
When the class needs another version number use serialver to generate a new one
Sun recommends using the program serialver to generate the serialVersionUID for your class
This recommendation is given in the context of Java's RMI for distributing objects over a network
This recommendation is made for security reasons
Using serialver
serialver is located in the same directory as javac
1. Compile your class, make sure that the variable:
static final long serialVersionUIDis not defined in the class
2. run serialver using the command line:
serialvar classname
3. The output of serialver is line of text to declare the variable serialVersionUID
Example of Using serialver
import java.io.Serializable; class Roger implements Serializable { public int lowBid; public Roger(int lowBid ) { this.lowBid = lowBid; } public String toString() { return " " + lowBid; } }
Put the above code in the file Roger.java
eli-> javac Roger.java eli-> serialver Roger Roger: static final long serialVersionUID = -8462350894591099987L;
Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.
visitors since 02-Dec-98