80 likes | 225 Views
Java Serialization. What is Serialization?. Allows the persistent storage of objects Uses the java.io.Serializable interface ObjectInputStream and ObjectOutputStream Allows you to save objects to file and load them at a later date
E N D
Java Serialization CS12420
What is Serialization? • Allows the persistent storage of objects • Uses the java.io.Serializable interface • ObjectInputStream and ObjectOutputStream • Allows you to save objects to file and load them at a later date • Really should only be used for temporary storage of objects CS12420
What is actually saved? • Only class name and object’s data is saved • If that data is an object, it is also saved • Each object is given a serial number • If an object has already been saved (e.g. within a graph) then only the serial number is saved • Methods are not saved • Static information not saved CS12420
An example Network structure: Nan granddaughter Stephanie Family daughter daughter daughter Mum Dad Serialized structure: 1 2 3 4 5 family dad mum nan stephanie daughter = 3 daughter = 5 members = 2 3 4 5 daughter = 5 granddaughter = 5 CS12420
To save and load structure To save the objects to file: FileOutputStream file = new FileOutputStream("data.ser"); ObjectOutputStream output = new ObjectOutputStream(file); output.writeObject(family); output.close(); To load the objects from file: FileInputStream file = new FileInputStream("data.ser"); ObjectInputStream input = new ObjectInputStream(file); Family family = (Family) input.readObject(); input.close(); Note .ser file naming convention CS12420
Indicate data to ignore • In some situations you may not require the serialized object to store all its data • Some classes cannot be serialized • To indicate that some data should not be stored use the keyword transient publicclass Test implements Serializable { publictransient PrintWriter pw; publicint total; ... CS12420
Making an object serializable • Implement the Serializable interface • Does not require any methods to be implemented • Implement the Externalizable interface • default behaviour only saves class name • must implement readExternal and writeExternal CS12420
Serialized Object V. Class Compatibility • Handled via the serialVersionUID value private static final long serialVersionUID = -2767605614048989439L; • View using serialver -show • Stored with serialized object • If not explicitly defined then a value is inserted at compile time • If the values are not the same - InvalidClassException CS12420