Demonstrating Serialization
The following is a very short and quick example to show how one
could easily demonstrate the serialization capabilities of
a piece of code. Granted, you will want to show more than saving Strings,
but this is a technique to work from.
This example is from "Developing Java Beans", by Englander, page 94.
The important parts for you are the dump() method in Container
and the application called Example5 afterwards.
Consider the following code:
import java.io.*;
class WidgetA implements Serializable
{
protected int val;
public WidgetA()
{
}
public void setValue(int value)
{
val = value;
}
public int getValue()
{
return val;
}
}
class WidgetB implements Serializable
{
protected int val;
protected WidgetA AA;
public WidgetB(WidgetA a)
{
AA = a;
}
public void setValue(int value)
{
val = value;
}
public int getValue()
{
return val;
}
}
class Container implements Serializable
{
protected int val;
protected WidgetA a1;
protected WidgetB b1;
public Container()
{
a1 = new WidgetA();
b1 = new WidgetB(a1);
}
public void setValue(int value)
{
val = value;
a1.setValue(val * 2);
b1.setValue(val * 3);
}
public int getValue()
{
return val;
}
public void dump()
{
System.out.println(val + ":" + a1.getValue() + ":" + b1.getValue());
}
}
Now consider an application used specifically to show that the above can
be serialized properly:
public class Example5
{
// the application entry point
public static void main(String[] args)
{
if (args[0].equals("save"))
{
Container c = new Container();
c.setValue(13);
try
{
FileOutputStream f = new FileOutputStream("Example5.tmp");
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(c);
s.flush();
}
catch (Exception e)
{
System.out.println(e);
}
c.dump();
}
else if (args[0].equals("restore"))
{
try
{
FileInputStream f = new FileInputStream("Example5.tmp");
ObjectInputStream s = new ObjectInputStream(f);
Container c = (Container)s.readObject();
c.dump();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
}
You can run the application with the following command (of course after
compilation):
The application first creates an instance of class Container
and sets its Value property to 13. This object creates instances
of WidgetA and WidgetB, and sets their Value
properties accordingly. It then creates the file called Example5.tmp.
Finally, it dumps information so one can see what is there. (Obviously, this
dump is what would be different for your use.)
Then, now that you have serialized the objects to file Example5.tmp,
you can reconstruct the objects by running the application again with:
Again, what the person running this program sees is dependent on what you
put in the Containers dump() method.
Obviously, note that for these examples, the arguments save and
restore were provided by the implementor to make it easy to
test the code. You, as the implementor, must provide a README
to tell me what to do to test your code. Who knows, you may have a beautiful
GUI that says save or load!