I am using the parcel object to pass the value from one process to another. I want to create a clone of the parcel object but I am not able to use clone() method If anyone 开发者_如何学JAVAknows how to create the copy of parcel please provide the solution.
The suggested solution is incomplete and will not work.
Here's a working solution:
(I have an object called message of type MessageDescriptor which I want to clone)
Parcel parcel = Parcel.obtain();
message.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
MessageDescriptor messageToBeSent = MessageDescriptor.CREATOR.createFromParcel(parcel);
parcel.recycle();
Assuming your object implements the Parcelable
interface, you should be able to do the following:
SomethingParcelable myObject = new SomethingParcelable();
Parcel p = Parcel.obtain();
myObject.writeToParcel(p, 0);
//must be called after unmarshalling your data.
p.setDataPosition(0);
SomethingParcelable myClonedObject = SomethingParcelable.CREATOR.createFromParcel(p);
Another way to create a copy without accessing object specific CREATOR use following generic method.
public <T extends Parcelable> T deepClone(T objectToClone) {
Parcel parcel = null;
try {
parcel = Parcel.obtain();
parcel.writeParcelable(objectToClone, 0);
parcel.setDataPosition(0);
return parcel.readParcelable(objectToClone.getClass().getClassLoader());
} finally {
if (parcel != null) {
parcel.recycle();
}
}
}
Also useful for copy constructors.
/**
* Copy request passed in.
*
* @param request Request To clone, null is accepted, just creates a blank object
*/
public RealTimeJourneyPlanRequest(@Nullable RealTimeJourneyPlanRequest request) {
if(request == null) return;
// Only copy if the request past in is not null
// Use the Parcel as its does deep cloning for us.
final Parcel parcel = Parcel.obtain();
request.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
// Copy into this object
readFromParcel(parcel);
// Clean parcel back into object pool
parcel.recycle();
}
精彩评论