I'm making an Android app which is sending 2 type of objects which implements the parcelable interface (lets call them objectA and objectB) over network as byte arrays. But on the receiving end I need to know which type of object arrived in the parcel. The parcel.readValue() method only returns Object, so on the receiving end I don't know which object should I recreate objectA or objectB. How can this be done? Do Parcels have some kind of metadata in them which describes the type of the original object?
Edit: the language is Java
Edit: Added example code
ObjectA objA = new ObjectA("uid", "description");
byte[] bytes = ParcelUtil.toBytes(objA); //this simulates the sending
Object rebuilt = ParcelUtil.rebuildFromBytes(bytes); //here I don't know what am I rebuilding, objectA or objectB
if(rebuilt instanceof Parcel){
Parcel p = (Parcel) rebuilt;
ObjectB oB = (ObjectB) p.readValue(ObjectB.class.getClassLoader());
if(oB.getUid() == null){
ObjectA oA = (ObjectA) p.readValue(ObjectA.class.getClassLoader()); //this will also be full of null values
}
}
I suppose you have access to the classes that could be the possible types of the object you have received. In Java you can simply use the instanceof operator to check what the object is that you have received:
if (yourObject instanceof YourClass) {
// Your code here
}
For Parcels there is a readValue method that accepts a class loader, call this method with your classes class loader and it should work, example:
Point pointFromParcel = (Point) parcel.readValue(Point.class.getClassLoader());
https://developer.android.com/reference/android/os/Parcel#readValue(java.lang.ClassLoader)
If you cannot know what object the wrapper class will be you could create a wrapper class with holds either a ObjectA or an ObjectB and a field to indicate which object the wrapper currently holds.