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.
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.
To use the Object. clone() method, we have to change a lot of syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object. clone() etc. We have to implement cloneable interface while it doesn't have any methods in it.
Java Object Cloning If you want to use Java Object clone() method, you have to implement the java. lang. Cloneable marker interface. Otherwise, it will throw CloneNotSupportedException at runtime.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With