Object Persistence and Object serialization CSNB534 Asma Shakil.

22
Object Persistence and Object serialization CSNB534 Asma Shakil

Transcript of Object Persistence and Object serialization CSNB534 Asma Shakil.

Object Persistence and Object serialization

CSNB534

Asma Shakil

Introduction

Data that can be read or written ranges from individual bytes to primitives datatypes and strings.

We can write a data structure (such as a sequence of a data records, composed of individual fields) out to a file.

How about if we wanted to store an entire object (composed of a series of member variables)?

Cont.

This requires each field of the object to be written individually; then at later time, each field would be read back and assigned to an object.

A complicated process! However, saving data is one of the most

important functions of software. The solution is to use object persistence.

What is object persistence?

The ability of an object to persist over time (if moved to a different machine, over space)

Most objects in Java Virtual Machine are fairly short-lived.

When there is no reference to the object, the memory space allocated to it is reclaimed by the automatic garbage collector thread.

All objects will die at some point in time resulting in a loss of reference.

Cont.

Object persistence allows an object to outlive the JVM that hosts it.

A custom class representing a key component of a system, a java.util.Vector list containing state data or java.util.Properties object containing system

settings are all good examples of objects that might

be important enough to be needed every time a program is run.

Object Serialization Object Serialization is the technique by which object

persistence is realized. It controls how the data that comprises an object’s

state information (the individual member variables, whether public, private or protected) is written as a sequence of bytes.

The serialized object might be sent over the network or saved to a disk so that it can be accessed at some point in the future.

This allows objects to move from one JVM to another whether located on the same machine or on a remote one.

Cont.

Serialization works by examining the variables of an object and writing primitives datatypes like numbers and characters to a byte stream.

It also caters to the situation where an object is inside another object.

If an object has a reference to an object which has a reference to another object, they are all saved together.

The set of all objects referenced is called a graph of objects and object serialization converts entire graphs to byte form.

Graphs

Vector

Object i Object n

OutputStream

1010100101

How serialization works

Any object that implements the java.io.Serializable interface may be serialized with only a few lines of code.

Implementing the java.io.Serializable interface requires no additional effort on the part of developers, other than adding the appropriate “implements” statement during the class declaration and declaring a no-argument constructor.

The interface acts as an indication that the developer endorses serialization – no method needs to be implemented to support serialization.

Example

Public class SomeClass extends SomeOtherClass implements java.io.Serializable {

public class SomeClass()

}

}

………

}

Issues

Legitimate reasons for not supporting serialization also exist.

For example, if an object contained very sensitive information it might be unwise to serialize it and save it to disk or send it over a network.

Suppose a class stored password data that can be easily obtained. To prevent individual member variables being serialized, they can be marked with the transient keyword.

Example

Public class UserAccount implements java.io.Serializable {

protected String username;protected transient String password;

public UserAccount( ){

….}

}

Reading and Writing Objects to Streams

The main point of serialization is to write an object out to a stream and to read it back

This is accomplished by using the java.io.ObjectOutputStream and java.io.ObjectInputStream classes

ObjectInputStream Class

Used to read a serialized object from a byte stream. To allow an object to be reconstituted back to its

original form The ObjectInputStream class implements the

ObjectInput interface which extends the DataInput interface. This mean that this class provides many methods with the same signature as DataInputStream.

Cont. Constructors

Protected ObjectInputStream ( ) – provides a default constructor for ObjectInputStream subclasses.

ObjectInputStream( InputStream input) – creates an object input stream connected to the specified input stream, capable of restoring serialized objects.

Methods Similar to the DataInputStream class

Because it can read primitive datatypes. Additional important method

Public final Object readObject( ) – reads a serialized object from the stream reconstructs it to its original state except for transient and static fields.

ObjectOutputStream Class

Serializes an object to a byte stream for the purpose of object persistence.

May be connected to any existing output stream such as a file or a networking stream.

Objects written to an ObjectOutputStream have all their member variables written.

If the object contains references to other objects, they too will be written. Therefore, the ObjectOutputStream can write entire object

graphs.

Cont.

Constructors Protected ObjectOutputStream ( ) – default

constructor. ObjectOutputStream (OutputStream output) – creates

an object output stream capable of serializing objects to the specified output stream.

Methods Void writeObject (Object object) – writes the specified

object to the output stream through object serialization

Serialization Example

Sample file (SerializationDemo.java)

Cont. In this example, the list created doesn’t die when the application

terminates – it is serialized to a FileOutputStream for later access

// Save list and terminateSystem.out.println ("Saving list");FileOutputStream fout = new FileOutputStream ( "list.out" );

// Construct an object output streamObjectOutputStream oout = new ObjectOutputStream ( fout );

// Write the object to the streamoout.writeObject (list);fout.close();System.exit(0);

FileInputStream fin = new FileInputStream ("list.out");

// Connect an object input stream to the listObjectInputStream oin = new ObjectInputStream ( fin );

try{

// Read the vector back from the listObject obj = oin.readObject();

// Cast back to a vectorlist = (Vector) obj;

}catch (ClassCastException cce){

// Can't read it, create a blank onelist = new Vector();

}catch (ClassNotFoundException cnfe){

// Can't read it, create a blank onelist = new Vector();

}

Cont.

When the application starts, it checks to see whether the serialized file exists. If so, the vector list is read back from the file along with any object references by the vector list

Summary

You have learned:

What streams are and how they work What readers and writers are and how they work How to connect filter streams to low-level streams How to connect readers and writers to streams About object serialization and how to read and write

objects