Download presentation
Presentation is loading. Please wait.
Published byMaurice Tyler Modified over 9 years ago
1
©SoftMoore ConsultingSlide 1 Serialization
2
©SoftMoore ConsultingSlide 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
3
©SoftMoore ConsultingSlide 3 Serialization (continued) Object Serialization Java Application Class A instance int x = 4 B b = Class B instance Serialized Object(s) in Arbitrary File Java Application Class A instance int x = 4 B b = Class B instance DeserializationSerialization JVM External Storage
4
©SoftMoore ConsultingSlide 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.
5
©SoftMoore ConsultingSlide 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
6
©SoftMoore ConsultingSlide 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.”
7
©SoftMoore ConsultingSlide 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();
8
©SoftMoore ConsultingSlide 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);
9
©SoftMoore ConsultingSlide 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
10
©SoftMoore ConsultingSlide 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 reference class 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]
11
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. ©SoftMoore ConsultingSlide 11
12
©SoftMoore ConsultingSlide 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.
13
©SoftMoore ConsultingSlide 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.
14
©SoftMoore ConsultingSlide 14 Serialization and JavaBean Instantiation JavaBeans can be created by 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
15
©SoftMoore ConsultingSlide 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.
16
©SoftMoore ConsultingSlide 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).
17
©SoftMoore ConsultingSlide 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(); }
18
©SoftMoore ConsultingSlide 18 Incompatible Changes If class has members added or removed, it becomes incompatible. An object of class java.io.InvalidClassException is thrown if you try to deserialize an incompatible object stream.
19
©SoftMoore ConsultingSlide 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 class protected static final long serialVersionUID = -2215190743590612933L; Now it’s marked as compatible with the old class.
20
Using readObject() for Object Migration Use readObject() if you want to force an old version of an object to be compatible. Implement readObject() method to make compatible changes private void readObject(ObjectInputStream stream) throws java.io.IOException { defaultReadObject(stream); // do stuff to make bean compatible } ©SoftMoore ConsultingSlide 20
21
©SoftMoore ConsultingSlide 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; }
22
©SoftMoore ConsultingSlide 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.
23
©SoftMoore ConsultingSlide 23 ObjectStreamField To limit serialization of fields Use transient modifier, or Declare the static field public final ObjectStreamField[] serialPersistentFields = {...}; initialized with instances of ObjectStreamField
24
©SoftMoore ConsultingSlide 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) }; }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.