Object Serialization in Java: Process, Use Cases, and Implementation, Slides of Java Programming

An overview of object serialization in java, including the process of converting objects to a serialized form and the use cases of rmi and lightweight persistence. It also covers the serialization api and its methods, such as objectoutputstream and objectinputstream, and provides an example of serializing and deserializing an object. The document also discusses the importance of handling other referenced objects correctly and making instances of classes serializable.

Typology: Slides

2011/2012

Uploaded on 07/13/2012

aim.high
aim.high 🇮🇳

4.2

(6)

48 documents

1 / 32

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download Object Serialization in Java: Process, Use Cases, and Implementation and more Slides Java Programming in PDF only on Docsity!

What

is^

Serialization

^ The

process

of^ storing

or^ retrieving

information

through

a^ standard

protocol

Use

of

Object

Serialization

^ RMI

(Remote

Method

Invocation)

^ communication

between

objects

via^

sockets

^ Lightweight

persistence

^ archival

of^ an

object

for^

use^

in^ a

later

invocation

of^ the

program^ ^ Object

lifetime

^ ^ created

by^ the

new^

operator

^ …^ exists

^ †^ destroyed

by^ the

Java^

VM’s

garbage

collector when

the^ program

no

longer

holds

a^ reference

to^ the

object

Serialization

API

5

CLASS

DESCRIPTION

ObjectOutputStream

Use this output stream to convert objects from thein-memory form to serial form. This streamimplements the ObjectOutput interface.

ObjectInputStream

Use this input stream to restore objects from theserial form. This stream implements theObjectInput interface.

Serializable

Implement this interface to indicate that the classcan be converted to a serial form and to definemethods that can be overridden to control theencoding of the class.

docsity.com

Serialization

API

(cont.)

7

Constructor/Method
Description

ObjectInputStream(InputStream)

Creates an ObjectInputStream that reads from the specifiedInputStream.

readObject()

Reads an object from the input stream; is the opposite ofwriteObject().

available()

Returns the number of bytes that can be read withoutblocking.

close()

Closes the input stream.

readInt()

Reads a 32-bit int from the stream.

defaultReadObject()

Reads the nonstatic and nontransient fields of the currentclass from the stream, ensuring the standard encodingformat. You can call this method only from the readObject()method of the class being decoded.

For more details consult the Java API.

docsity.com

Serialization

API

(cont.)

8

^ The Serializable interface defines no methods but is an indicator that theclass is compatible with serialization and may have private readObject()and writeObject() methods to control serialization. ^ Only the data in the objects and the declarations of the classes areencoded in the byte stream; the Java VM bytecodes that implement themethods of the classes are not stored when an object is serialized.
^ When the object is retrieved from the stream, the class declaration isread and the normal class-loading mechanisms are used to load thecode. ^ If a matching class is not found, readObject() throwsClassNotFoundException.

docsity.com

Serializing

Objects

‐reading

10

^ Reading objects from a stream : ^ ObjectInputStream must be constructed on another stream.(Here, the objects were archived in a file, so the code constructs anObjectInputStream on a FileInputStream.) ^ Use ObjectInputStream's readObject method to read the String and the Dateobjects from the file. ^ The objects must be read from the stream in the same order in which they werewritten. Note that the return value from readObject is an object that is cast toand assigned to a specific type.

FileInputStream in = new FileInputStream("theTime");ObjectInputStream s = new ObjectInputStream(in);String today = (String)s.readObject();Date date = (Date)s.readObject();

Example^ Object

object
=^ new
javax.swing.JButton("push
me")
try^ {
//^ Serialize
to^ a
file
ObjectOutput
out^
=^ new
ObjectOutputStream(new
FileOutputStream(
"filename.ser"
out.writeObject(object); out.close();
//^ Serialize
to^ a
byte
array
ByteArrayOutputStream
bos^
=^ new
ByteArrayOutputStream()
out^ =
new
ObjectOutputStream(bos)
out.writeObject(object); out.close();
//^ Get
the^
bytes
of^ the
serialized
object
byte[]
buf^
=^ bos.toByteArray();
}^ catch
(IOException
e)^ {^

Serializing

Objects

(cont.)

13

/** pstruct is an object containing fields of different types, e.g. String, double, etc.*/obj_outs.writeObject(pstruct.product_id);obj_outs.writeObject(pstruct.product_name);obj_outs.writeObject(pstruct.product_description);obj_outs.writeObject(new Double(pstruct.price));obj_outs.writeObject(pstruct.currency);obj_outs.writeObject(new Boolean(pstruct.soft_good_p));obj_outs.writeObject(new Boolean(pstruct.for_sale_p));obj_outs.writeObject(pstruct.terms_and_conditions);data = b_outs.toByteArray();obj_outs.close();b_outs.close();

Serializing

Objects

(cont.)

14

/** at this point, byte buffer contains the serialized form of pstruct //* reconstruct pstruct as follows */ByteArrayInputStream b_ins = new ByteArrayInputStream(data);ObjectInputStream obj_ins = new ObjectInputStream(b_ins);

Serializing

Objects

16

^ Complication :^ Correct handling of other referenced objects. The object to be serializedmust include a copy of all the objects it references, all the objects thoseobjects reference, and so on. (All these objects have to be included bythe serialized object, because they are part of its total state.) ^ Note :^ The writeObject() method does not explicitly synchronize on the objectbeing serialized. If you have multiple threads using the same object, andone thread can possibly be serializing an object while another thread ismanipulating fields of the same object, you must take steps to be threadsafe (e.g. add explicitly synchronization code, make an object clonebefore serializing).

Object

Serialization

for

Classes

17

^ Making instances of your classes serializable
Just add the implements Serializable clause to your class declaration :  No methods needed (serialization is handled by the defaultWriteObjectmethod of ObjectOutputStream).  Deserialization with the defaultReadObject method inObjectInputStream.  Default behavior is good enough, but can be slow, and a class mightwant more explicit control over the serialization.

public class MySerializableClass implements Serializable {

The

Externalizable

Interface

^ Differs

from

Serializable

in^ :

^ the

amount

of^ control

in^ the

serialization

process

^ the

extent

of^ customizations

^ writeObject,

readObject

^ responsible

for^ serializing

only

the^ immediate

class.

^ Any

serialization

required

by^ the

superclasses

is^ handled

automatically.

^ Class

^ {^

explicitly

coordinate

with

its^ superclasses

to^ serialize

itself

}^ 

implementing

the^ Externalizable

interface.

^ +^

:^ Complete,

explicit

control

of^ the

serialization

process.

^!^

:^ Only

the^ class

identification

of^ the

object

is^ automatically

saved

by^ the

stream.

The^ class

is^ responsible

for^ writing

and^

reading

its^ contents,

and^

it^ must

coordinate

with^

its^ superclasses

to^ do

so^ (whether

or^ not

the^ state

of^ superclasses

and^

which

fields

are^ stored).

Externalization

API

^ writeExternal()

must

encode

the^ data

of^ the

object

in^ a^ form

and^

sequence

supported

by^ readExternal().  Does

not^ support

code

versioning

^ you

must

provide

your

own

versioning

approach.

^ Above

methods

are^ public

^ security

risk^

(a^ client

may be^ able

to^ write

or^ read

information

in^ the

object

other

than

by^ using

its^ methods).

20

Method (public)
Description

readExternal(ObjectInput)

The object implements this method to restore its contents bycalling the methods of DataInput for primitive types andreadObject() for objects, strings and arrays.

writeExternal(ObjectOutput)

The object implements this method to save its contents by callingthe methods of DataOutput for its primitive values or calling thewriteObject() method of ObjectOutput for objects, strings andarrays.

For more details consult the Java API.