java – how to clone an object in android?-ThrowExceptions

Exception or error:

What would be the best way to copy/clone an object in java/android?

rlBodyDataObj rlbo = bdoTable.get(name);

Right now the code assigns an object from a hashTable, yet I need to get a clone of it, so that I’d be able to use it multiple times.

How to solve:

Make sure that your DataObj class implements Cloneable and add the following method

protected Object clone() throws CloneNotSupportedException {
        return super.clone();
}

Then you should be able to call (DataObj)rlBodyDataObj.clone(); to get a clean copy (note the cast).

###

class Test implements Cloneable
  {
   ...
      public Object clone()
      {
          try
      {
              return super.clone();
          }
      catch( CloneNotSupportedException e )
      {
              return null;
          }
      } 
  ...
  }

###

you can implements Parcelable (easy with studio plugin), and then

public static <T extends Parcelable> T copy(T orig) {
    Parcel p = Parcel.obtain();
    orig.writeToParcel(p, 0);
    p.setDataPosition(0);
    T copy = null;
    try {
        copy = (T) orig.getClass().getDeclaredConstructor(new Class[]{Parcel.class}).newInstance(p);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return copy;
}

###

Sometimes you need to modify some fields before returning from the clone() method.

Check this : http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone().
I pasted the relevant part here for convenience:

“By convention, the object returned by this method should be
independent of this object (which is being cloned). To achieve this
independence, it may be necessary to modify one or more fields of the
object returned by super.clone before returning it. Typically, this
means copying any mutable objects that comprise the internal “deep
structure” of the object being cloned and replacing the references to
these objects with references to the copies. If a class contains only
primitive fields or references to immutable objects, then it is
usually the case that no fields in the object returned by super.clone
need to be modified.”

###

i wish to implement with :
copy constructor

class DataObj {
  private String tag;

  public DataObj(DataObj another) {
    this.tag= another.tag; // you can access  
    ...
  }
}

Every object has also a clone method which can be used to copy the object, but It’s way too easy to create a class and do improper clone method. If you are going to do with implement clone method, read at least what Joshua Bloch has to say about it in Effective Java.

###

You have to specify on your class that it implements Cloneable interface and you have to override clone method inside that class. By Default it will use clone method of Object class.

Leave a Reply

Your email address will not be published. Required fields are marked *