2

I want to clone a Parcel object (not parcelable).

I can't use clone() method since it is protected. I also can't call it using reflection since Parcel class doesn't implement 'clonable'

I tried to perform the solution of issue: Create a copy of parcel object but it does not apply for Parcel type itself - and the reason for that is that 'writeToParcel' is not defined for Parcel type itself. So for the object 'Parcel a', a.writeToParcel(parcel, 0) won't compile.

Community
  • 1
  • 1
morang
  • 151
  • 2
  • 10

2 Answers2

3

Use Parcel.appendFrom()

This is more efficient than marshalling and unmarshalling and it won't lose any data about object references or FileDescriptors in the parcel.

Source: Overheard Android framework developer talking about this, and decided to update the Stackoverflow question.

Brian Attwell
  • 9,239
  • 2
  • 31
  • 26
-1

You can do it by marshalling/unmarshalling

byte[] rawData = original.marshall();
Parcel clone = Parcel.obtain();
clone.unmarshall(rawData, 0, rawData.length);
clone.setDataPosition(original.dataPosition());

It doesn't work for all Parcels though. I think it fails on Parcels with an active object, but I haven't tested to make sure.

Black Mantha
  • 1,147
  • 8
  • 11
  • Down-voting because it's an incomplete solution, and not really performant. Parcel#appendFrom is the way to go. – xaethos Jan 06 '15 at 19:17