©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows...

24
©SoftMoore Consulting Slide 1 Serialization

Transcript of ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows...

Page 1: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 1

Serialization

Page 2: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 2

Serialization

• Allows objects to be written to a stream

• Can be used for persistence (writing to a file stream) or for socket communication

• Most objects easy to serialize

• Serialization can be customized when necessary

• Default file extension is “.ser”

• serialize - to save

• deserialize - to load

Page 3: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 3

Serialization(continued)

Object Serialization

Java Application

Class A instance

int x = 4

B b =

Class B instance

SerializedObject(s)

in ArbitraryFile

Java Application

Class A instance

int x = 4

B b =

Class B instance

DeserializationSerialization

JVM JVM

External Storage

Page 4: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 4

Java Serialization/Deserialization

• Serialization: write object as a sequence of bytes to a stream

• Deserialization: recreate brand new object on the other end with the original object’s data

Note: Deserialization does not call the default constructor. It simply creates a blank object and fills in the fields with values retrieved via deserialization.

Page 5: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 5

Serialization Interfaces

• A class to be serialized implements either the Serializable interface or the Externalizable interface

• Most JavaBeans can use Serializable

• Objects that implement Externalizable have complete control over serialized state– can save and restore as any needed data format– all work must be done by programmer– must handle references to other objects (graphs)– must handle superclass data

Page 6: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 6

java.io.Serializable

• Classes that implement the interface java.io.Serializable are marked as serializable.

• Subclasses are also marked

• Magically, all non-static and non-transient fields will be serialized.– Actually, it’s not magic, it’s Reflection – (It’s done with mirrors) (ha ha)

• Serializable is an empty interface – just a marker.It’s a promise: “I really am serializable, trust me.”

Page 7: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 7

Writing an Object to a Stream

Date now = new Date();System.out.println("This is now: " + now);

FileOutputStream fOut = new FileOutputStream("test.out");ObjectOutputStream out = new ObjectOutputStream(fOut);

out.writeObject(now);

out.close();

Page 8: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 8

Reading an Object from a Stream

FileInputStream fIn = new FileInputStream("test.out");ObjectInputStream in = new ObjectInputStream(fIn);

Date then = (Date) in.readObject();

System.out.println("That was then: " + then);

Page 9: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 9

Serialization Makes A Copy

• Serialization writes a copy of the object and all objects that it references, recursively.

• If out and in point to the same file…Date d1 = new Date();out.writeObject(d1);Date d2 = (Date) in.readObject();

d1 and d2 are different objects with the same value

Page 10: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 10

Serialization Writes All Objects

• Serialization writes a graph of objects– this object– all objects this object references– all objects those objects reference– and so on

• It takes care of loops by writing a referenceclass A { B b } ;class B { A a }; A a = new A();B b = new B();a.b = b;b.a = a;– serialization writes something like

1:A =[b=2], 2:B =[a=1]

Page 11: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting

Not All Objects Are Serializable

• Any object that doesn’t implement Serializable

• Any object that would pose a security risk(e.g., FileInputStream)

• Any object whose value depends on VM-specific information (e.g., Thread)

• Any object that contains an unserializable object; i.e., any object that contains a non-static, non-transient, unserializable object, recursively.

Slide 11

Page 12: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 12

NotSerializableException

• Thrown if you try to serialize or deserialize an object that is not serializable.

• For example, maybe you subclassed a serializable object and added some unserializable members.

Page 13: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 13

Transient Fields

• Data fields that are marked transient are not written to the stream.

• Unserializable elements need to be marked transient (Thread, Image, ...).

• Fields that hold sensitive information should always be transient.– Transient fields must be restored when the object is read from

stream.– You may need to implement the readObject() method.

Page 14: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 14

Serialization and JavaBean Instantiation

• JavaBeans can be createdby using “new”MyBean b = new MyBean();

or

by instantiating a serialized prototype(stored in .ser file inside JavaBean .jar file)Beans.instantiate(null, "mypackage.MyBean");

• Method java.beans.Beans.instantiate()– replacement for new– loads the JavaBean and instantiates it– returns a reference to the new object

Page 15: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 15

Customizing Serialization

• A Serializable class can implement writeObject() and/or readObject() methods to customize serialization.

• Can write out all class data manually or use default input and output methods.

Page 16: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 16

Customizing Serialization(continued)

• Implementing writeObject()– Use ObjectOutputStream method defaultWriteObject() to write out default representation.

– Then write extra data using OutputStream methods.

• Implementing readObject()– Use ObjectInputStream method defaultReadObject()

to read in default representation.– Then read extra data using InputStream methods

(or, calculate values for transient variables).

Page 17: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 17

Example: writeObject()/readObject()

private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(magicNumber); }

private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); magicNumber = stream.readInt(); }

Page 18: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 18

Incompatible Changes

• If class has members added or removed, it becomes incompatible.

• An object of class java.io.InvalidClassExceptionis thrown if you try to deserialize an incompatible object stream.

Page 19: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 19

Serial Version

If the changes were actually compatible,

1. Find out the Serial Version UID of the original class using the serialver utility

2. Add a member variable to the changed classprotected static final long serialVersionUID = -2215190743590612933L;

Now it’s marked as compatible with the old class.

Page 20: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

Using readObject() forObject Migration

• Use readObject() if you want to force an old version of an object to be compatible.

• Implement readObject() method to make compatible changesprivate void readObject(ObjectInputStream stream) throws java.io.IOException { defaultReadObject(stream); // do stuff to make bean compatible }

©SoftMoore Consulting Slide 20

Page 21: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 21

Object Validation

• An object can register as a validator.

• The validator can make sure an object is in a valid state after it’s been read.public interface ObjectInputValidation { public void validateObject() throws InvalidObjectException; }

Page 22: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 22

Serialization and JDBC/Networking

• Serialization can be used to store Java object structures in a relational database.– serialize objects into a stream– store stream as BLOB in database

• Serialization can be used to send objects across a network using sockets.

Page 23: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 23

ObjectStreamField

To limit serialization of fields

• Use transient modifier,

or

• Declare the static fieldpublic final ObjectStreamField[] serialPersistentFields = {...};

initialized with instances of ObjectStreamField

Page 24: ©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.

©SoftMoore Consulting Slide 24

Example: ObjectStreamField

public class FooBar implements Serializable { private Foo foo; private int bar; private String passwd;

public final static ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("foo", Foo.class), new ObjectStreamField("bar", int.class) }; }