Monday, October 22, 2012

How to achieve deepCopy() of an Object in Java


Subject :

    we might need to get a deep copy of a specific Java object, For eg : an EmployeeDTO ( POJO - Plain Old Java Object) may contain collection of other Object, Again each child object can have separate object internally . If  you want to clone the main object then you need to perform a deep copy ,

Solution


  public static Object deepCopy(Object pObject)
  {
    String methodName = "deepCopy(Object)";
    _logger.entering(CLAZZ_NAME, methodName);
    ObjectOutputStream mObjOutStrm = null;
    ObjectInputStream mObjInStrm = null;
    try
    {
      ByteArrayOutputStream mByteArrOutStrm = new ByteArrayOutputStream();
      mObjOutStrm = new ObjectOutputStream(mByteArrOutStrm);
      // serialize and pass the object
      mObjOutStrm.writeObject(pObject);
      mObjOutStrm.flush();
      ByteArrayInputStream bin =
        new ByteArrayInputStream(mByteArrOutStrm.toByteArray());
      mObjInStrm = new ObjectInputStream(bin);
      // return the new object
      return mObjInStrm.readObject();
    }
    catch (Exception ex)
    {
      _logger.logp(Level.FINER, CLAZZ_NAME, methodName,
                   "Exception in deepCopy = " + ex);
      return pObject;
    }
    finally
    {
      try
      {
        mObjOutStrm.close();
        mObjOutStrm.close();
      }
      catch (IOException ioe)
      {
        _logger.log(Level.FINER,
                    "IO Exception in Deep Copy while closing stream");
      }
      finally
      {
        _logger.exiting(CLAZZ_NAME, methodName);
      }
    }
  }

No comments:

Post a Comment