Java Serialization - PowerPoint PPT Presentation

1 / 8
About This Presentation
Title:

Java Serialization

Description:

dad. 2. mum. nan. stephanie. 3. 4. 5. daughter = 5. granddaughter = 5. daughter = 3. members = 2 3 4 5. daughter = 5. Network structure: Serialized structure: U.W. ... – PowerPoint PPT presentation

Number of Views:184
Avg rating:3.0/5.0
Slides: 9
Provided by: raerich
Category:

less

Transcript and Presenter's Notes

Title: Java Serialization


1
Java Serialization
2
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

3
What is actually saved?
  • Only class name and objects 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

4
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
5
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.s
    er")
  • ObjectInputStream input new ObjectInputStream(fi
    le)
  • Family family (Family) input.readObject()
  • input.close()
  • Note .ser file naming convention

6
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
  • public class Test implements Serializable
  • public transient PrintWriter pw
  • public int total
  • ...

7
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

8
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
Write a Comment
User Comments (0)
About PowerShow.com