The steps for making a deep copy using serialization are:
Ensure that all classes in the object's graph are serializable
1.Create input and output streams.
2.Use the input and output streams to create object input and object output streams.
3.Pass the object that you want to copy to the object output stream.
4.Read the new object from the object input stream and cast it back to the class of the object you sent.
The class for serialization
import java.io.*;
import java.util.*;
import java.awt.*;
public class ObjectCloner
{
// so that nobody can accidentally create an ObjectCloner object
private ObjectCloner(){}
// returns a deep copy of an object
static public Object deepCopy(Object oldObj) throws Exception
{
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try
{
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
// return the new object
return ois.readObject(); // G
}
catch(Exception e)
{
System.out.println("Exception in ObjectCloner = " + e);
throw(e);
}
finally
{
oos.close();
ois.close();
}
}
}
The main class
import java.util.*;
import java.awt.*;
public class Driver1
{
static public void main(String[] args)
{
try
{
// get the method from the command line
String meth;
if((args.length == 1) &&
((args[0].equals("deep")) || (args[0].equals("shallow"))))
{
meth = args[0];
}
else
{
System.out.println("Usage: java Driver1 [deep, shallow]");
return;
}
// create original object
Vector v1 = new Vector();
Point p1 = new Point(1,1);
v1.addElement(p1);
// see what it is
System.out.println("Original = " + v1);
Vector vNew = null;
if(meth.equals("deep"))
{
// deep copy
vNew = (Vector)(ObjectCloner.deepCopy(v1)); // A
}
else if(meth.equals("shallow"))
{
// shallow copy
vNew = (Vector)v1.clone(); // B
}
// verify it is the same
System.out.println("New = " + vNew);
// change the original object's contents
p1.x = 2;
p1.y = 2;
// see what is in each one now
System.out.println("Original = " + v1);
System.out.println("New = " + vNew);
}
catch(Exception e)
{
System.out.println("Exception in main = " + e);
}
}
}
No comments:
Post a Comment