Using Parcel to clone an object?
I have a class which has implemented Parcelable. Can I do something like the following to create a new instance of a class?:
Foo foo = new Foo("a", "b", "c");
Parcel parcel = Parcel.obtain();
foo.writeToParcel(pa开发者_如何学Gorcel, 0);
Foo foo2 = Foo.CREATOR.createFromParcel(parcel);
I'd like foo2 to be a clone of foo.
---------------------- update -------------------------------
The above does not work (all Foo members are null in new instance). I'm passing Foos between activities just fine, so the Parcelable interface is implemented ok. Using the below which works:
Foo foo1 = new Foo("a", "b", "c");
Parcel p1 = Parcel.obtain();
Parcel p2 = Parcel.obtain();
byte[] bytes = null;
p1.writeValue(foo1);
bytes = p1.marshall();
p2.unmarshall(bytes, 0, bytes.length);
p2.setDataPosition(0);
Foo foo2 = (Foo)p2.readValue(Foo.class.getClassLoader());
p1.recycle();
p2.recycle();
// foo2 is the same as foo1.
found this from the following q: How to use Parcel in Android?
This is working ok, I can go with this but it is extra code, not sure if there's a shorter way to do it (other than properly implementing a copy constructor...).
Thanks
There is a shorter way:
Foo foo1 = new Foo("a", "b", "c");
Parcel p = Parcel.obtain();
p.writeValue(foo1);
p.setDataPosition(0);
Foo foo2 = (Foo)p.readValue(Foo.class.getClassLoader());
p.recycle();
I had the same problem and here is my solution:
Parcel p = Parcel.obtain();
foo.writeToParcel(p, 0);
p.setDataPosition(0); // <-- this is the key
Foo foo2 = Foo.CREATOR.createFromParcel(p);
p.recycle();
Yes, assuming that your parcel implementation correctly writes and reads all of the variables in Foo, that should create a clone.
I have done a Utility class with a static method that takes any parcelable and clone it.
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelUtils {
public static <T extends Parcelable> T clone(T object) {
Parcel p = Parcel.obtain();
p.writeValue(object);
p.setDataPosition(0);
Class<? extends Parcelable> c = object.getClass();
@SuppressWarnings("unchecked")
T newObject = (T) p.readValue(c.getClassLoader());
p.recycle();
return newObject;
}
}
精彩评论