Object Serialization - Fidelio!

farflungconvyancerSoftware and s/w Development

Dec 2, 2013 (3 years and 8 months ago)

102 views

Object Serialization 
(2011.06.01)
Frank Ducrest
Object Serialization
2
Object Serialization

allows reading and writing whole objects

classes 
ObjectInputStream
 and 
ObjectOutputStream
 
read and write objects

used for RMI (remote method invocation) and 
lightweight persistence
http://java.sun.com/j2se/1.5.0/docs/guide/serialization/
Serialization for a Class

object 
serializable
 if its class implements 
Serializable
 
interface

interface 
Serializable
 
empty, just a marker

Serializable
 interface:
public interface java.io.Serializable {}
Object Serialization
3
Serialization for a Class

all objects and final primitive variables in a class that 
implements 
Serializable
 can be:
­  
serialized
 through the 
defaultWriteObject
 
method of class 
ObjectOutputStream
­  
deserialized
 throught the 
defaultReadObject
 
method of class 
ObjectInputStream
http://download.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html
http://download.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html
Object Serialization
4
Object Serialization
5
Object Serialization: Writing

steps:
1) get an output stream
2) wrap output stream in 
ObjectOutputStream
 object
3) write via 
ObjectOutputStream
 
class 
writeObject
     
    
method
4) write primitive types via specific methods

example (from “The Java
tm
 Tutorials”):
FileOutputStream out
= new FileOutputStream(theTime);
ObjectOuputStream s = new ObjectOutputStream(out);
s.writeObject(Today);
s.writeObject(new Date());
s.flush();
http://download.oracle.com/javase/tutorial/
http://download.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html
Object Serialization: Reading

steps:
1) get an input stream
2) wrap input stream in 
ObjectInputStream
 object
3) read via 
ObjectInputStream
 class 
readObject
 method
4) read primitive types via specific methods

example (from “The Java
tm
 Tutorials”):
FileInputStream in = new FileInputStream(theTime);
ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
http://download.oracle.com/javase/tutorial/
http://download.oracle.com/javase/6/docs/api/java/io/ObjectInputStream.html
Object Serialization
6