Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Ezclone With Serialization

Ezclone With Serialization

Java Programming Tricks

EZClone with serialization:

 Cloning in Java is tedious to implement. You need to 
 
 1. have the class implement cloneable 
 
 2. implement the clone method 
 
 public void clone 
 
 {    try 
 
 { X ret = super.clone(); 
 
 // now clone all object data fields and" copy all number Data fields 
 
 ret.objdata1 = objdata1.clone 
 
 ret.numdata1 = numdata1; 
 
 return ret; 
 
 }   catch(CloneNotSupportedException) 
 
 {  return null; 
 
 } 
 
 } 
 
 Tip 
 
 Use serialization for cloning. As long as all data fields are serializable.
 the entire cloning process can be automated. 
 
 class EZClone implements Cloneable, Serializable 
 
 { public Object clone() 
 
 try 
 
 {     ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
 
 ObjectOutputStream out = new ObjectOutputStream(bout); 
 
 out.writeQbject(this); 
 
 out.close(); 
 
 ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); 
 
 ObjectInputStream in = new ObjectInputStream(bin); 
 
 Object ret = in.readObject(); 
 
 in.close(); 
 
 return ret; 
 
 } catch(Exception e) 
 
 {  return null; 
 
 } 
 
 } 
 
 class X extends EZClone 
 
 { // no clone necessary 
 
 }
 

Partners