Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Aug 19, 2002

Get the Deep Copy of Any Object


This generic class will help to obtain a deep copy of any object and cast it to the Object Type:
 
public class ObjectCloner
{

   private ObjectCloner(){}

   // returns a deep copy of an object
   public static 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();
      }
   }
}
SubbaRao Karanam
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date