Download ObjectStreams and Object Serialization Object Serialization Object

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
Object Serialization
ObjectStreams
and
Object Serialization
takes an object instance and creates a
decomposed byte representation
object
byte representation of
any Java object
Object Serialization
Java’s RMI (Remote Method Invocation) uses
object serialization to move an object from one
location to another
JavaBeans and Object
Serialization
JavaBeans uses object serialization to
save the state of an object and
reconstruct the object on demand
mybean.jar
Bean is packaged
in jar file
object
object is
reconstructed
object
myobject.ser
bytes
bytes
1
Object Streams and Networks
ObjectStreams are a
subclass of InputStream
InputStream
ObjectStreams
Constructor requires one
argument – an underlying
InputStream
Socket
myFoo
bbbbbbbbbbbbbbbbbbb Socket
public ObjectInputStream(InputStream) throws IOException;
class MyFoo implements
Serializable {
MyFoo myFoo = new MyFoo();
public int k;
myFoo.x = 3.14;
public float f;
objStream.writeObject(myFoo);
public double x;
}
try {
ObjectStream writing
ObjectInputStream
FileInputStream fin = new FileInputStream(“my.dat”);
ObjectInputStream oin = new ObjectInputStream(fin);
try {
Point p = new Point(23,43);
ObjectStream reading
FileInputStream fin = new
FileInputStream(“point.ser”);
FileOutputStream fout = new
FileOutputStream(“point.ser”);
ObjectInputStream oin = new
ObjectInputStream(fin);
ObjectOutputStream oout = new
ObjectOutputStream(fout);
Object o = oin.readObject();
oout.writeObject(p);
Point p = (Point)o;
oout.close();
oin.close();
}
}
catch (Exception e) {System.out.println(e);}
catch (Exception e) {System.out.println(e);}
may throw IOException, ClassNotFoundException or
OptionalDataException (if file not proper format for objects)
2
ObjectInputStream
returns Objects
Reading Objects -- must cast
Point p = (Point) oin.readObject();
returns TYPE = Object
java.io.Serializable
• An Interface with no methods
• A class must implement Serializable in order
for its instances to be serialized over
ObjectOutputStream and
ObjectInputStream
• Trying to serialize a non-serializable object
will throw an ObjectStreamException
(subclass of IOException)
writeObject()
• Writes the value of all fields
– private fields
– fields inherited from superclass
• When field refers to an object,
writeObject is invoked recursively on that
object
• If two objects refer to each other,
serialization will detect it and not continue
infinitely
What gets Serialized??
class Region
implements Serializable{
Account [ ] acct;
only if Account
int idNumber;
class is
String idString;
serializable
…
primitive types
}
always get serialized
3
Not all classes are
serializable - why?
• Tied to native code:
– java.util.zip.Deflater
• State depends on JVM
– java.lang.Thread
• Security Risk
– java.lang.SecurityManager
• Class mainly holds static methods
– java.lang.Math
• Programmer forgot to think about it
What can prevent
serialization?
• References to non-serializable objects
class Region
implements Serializable{
Account [ ] acct;
Socket mySocket;
the Socket class
int idNumber;
is not serializable
String idString;
…
}
Not all objects (and data)
should be serialized
• Platform specific objects
– e.g FileDescriptors
• To prevent a data field from being
serialized, declare it transient
– private transient float f;
class Region
implements Serializable{
Account [ ] acct;
transient Socket mySocket;
int idNumber;
String idString;
…
will not try and
}
serialize the Socket
4
Versioning
• When writing to stream, only the object
state and name of file are written
• No guarantee that the class will have the
same internals when it’s deserialized
• The class may change with different:
– Static data
– Methods
– Instance variables
Waking up to a new class
modified class
definition
NOT OK
changes!
•new class name
•remove instance field
•change type of instance field
•change name of instance field
•change from non-static to static
•changing superclass
Waking up to a new class
modified class
definition
OK
changes!
•new constructors
•changes to static fields
•changes to transient fields
•adding instance variables
•changing private, public, protected
Versioning IDs
• Every Java class has a unique system
identifier (SUID)
• If you include it in your class the
deserializer will look to it for
guidance as for class compatibility
• For any class use command prompt:
• >serialver MyClass
MyClass: static final long serialVersionID = 87466352840L;
5
class Region
implements Serializable{
static final long serialVersionID = 874663840L;
Account [ ] acct;
transient Socket mySocket;
int idNumber;
String idString;
…
ObjectStreams allow you to
implement your own
Persistence
mechanisms
}
Object Persistence
Object Persistence...
uses data
collects data
program1
DISK
stores data as
object
retreives
object
program2
DISK
6
public static void main (String [ ] args)
throws IOException,
ClassNotFoundException {
double doubleDat [ ] = {12.2, 33.5, 99.45};
double newDat [ ];
if (option == 'w')
writeObjectData(doubleDat, fname);
else if (option == 'r') {
newDat = readObjectData(fname);
for (int i=0; i< newDat.length; i++)
System.out.println( newDat[i] );
}
}
char option = args[0].charAt(0);
String fname = args[1];
…...
public static void writeObjectData(
double[ ] data,
String file) throws IOException {
public static double [ ] readObjectData (String file)
throws IOException, ClassNotFoundException {
InputStream fin
= new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fin);
OutputStream fout = new FileOutputStream(file);
ObjectOutputStream out = new
ObjectOutputStream(fout);
double [ ] data = (double [ ] ) in.readObject() ;
out.writeObject (data);
out.close();
}
in.close();
return data;
}
writes entire array in one statement
7
class ObjectToSave implements Serializable {
static final long serialVersionUID
= 7482918152381158178L;
private int i;
private String s;
private transient double d;
public ObjectToSave( int i, String s, double d ) {
this.i = i;
this.s = s;
this.d = d;
}
public String toString() {
return "i = " + i + ", s = " + s + ", d = " + d;
}
public class ObjectSaver {
private static final String FILE_NAME
= "objects.ser";
/** Test method for the class
* @param args not used
*/
public static void main( String[] args ) {
try {
// create the object to be serialized
ObjectToSave ots
= new ObjectToSave( 57, "pizza", 3.14 );
// create the target File object and erase
// any already existing file
File objectFile = new File( FILE_NAME );
if ( objectFile.exists() ) {
objectFile.delete(); }
private void readObject( ObjectInputStream ois )
throws ClassNotFoundException, IOException {
System.out.println( "deserializing..." );
ois.defaultReadObject();
System.out.println( "deserialized" );
}
private void writeObject( ObjectOutputStream oos )
throws IOException {
System.out.println( "serializing..." );
oos.defaultWriteObject();
System.out.println( "serialized" );
}
// open the file, create the output stream
// and write the object
FileOutputStream fos
= new FileOutputStream( objectFile );
ObjectOutputStream oos
= new ObjectOutputStream( fos );
oos.writeObject( ots );
oos.close();
8
// reopen the file and retrieve the object
FileInputStream fis
= new FileInputStream( objectFile );
ObjectInputStream ois
= new ObjectInputStream( fis );
ObjectToSave retrieved
= (ObjectToSave) ois.readObject();
ois.close();
System.out.println( retrieved );
9