12/14/09

Java-Object Serialization

.Object serialization: the capability to read and write an object using stream.
.Reflection:the capability of one object to learn details about another object
.Remote method invocation: the capability to query another object to investigate its features and call its methods.

A programming concept involved in object serialization is persistence - the capability of an object to exist and function outside the pragram that create it.

An object indicates that it can be used with streams by implementing the Serializable interface. This interface, which is part of the java.io package, differs from other interfaces you have worked withit does not contain any methods that must be included in the classes that implement it. The sole purpose of Serializable is to indicate that objects of that class can be stored an retrieved in serial form.
The following code creates an output stream and an associated object output stream:

FileOutputStream disk = new FileOutputStream("SavedObject.dat");

ObjectOutputStream obj = new ObjectOutputStream(disk);

The object to Disk program:
----------
import java.io.*;

import java.util.*;
public class ObjectToDisk {
public static void main(String[] arguments) {
Message mess = new Message();
String author = "Sam Wainwright, London";
String recipient = "George Bailey, Bedford Falls";
String[] letter = { "Mr. Gower cabled you need cash. Stop.",
"My office instructed to advance you up to twenty-five",
"thousand dollars. Stop. Hee-haw and Merry Christmas." };
Date now = new Date();
mess.writeMessage(author, recipient, now, letter);
try {
FileOutputStream fo = new FileOutputStream("Message.obj");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(mess);
oo.close();
System.out.println("Object created successfully.");
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}
class Message implements Serializable {
int lineCount;
String from, to;
Date when;
String[] text;
void writeMessage(String inFrom,
String inTo,
Date inWhen,
String[] inText) {
text = new String[inText.length];
for (int i = 0; i < inText.length; i++)
text[i] = inText[i];
lineCount = inText.length;
to = inTo;
from = inFrom;
when = inWhen;
}
}
--------------
The object from disk program:
import java.io.*;

import java.util.*;
public class ObjectFromDisk {
public static void main(String[] arguments) {
try {
FileInputStream fi = new FileInputStream("message.obj");
ObjectInputStream oi = new ObjectInputStream(fi);
Message mess = (Message) oi.readObject();
System.out.println("Message:\n");
System.out.println("From: " + mess.from);
System.out.println("To: " + mess.to);
System.out.println("Date: " + mess.when + "\n");
for (int i = 0; i < mess.lineCount; i++)
System.out.println(mess.text[i]);
oi.close();
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
}
}