有什么方法可以知道 Android 上的 Parcel 中的对象是什么类型?

Is there any way to know what type of object is in a Parcel on Android?

我正在制作一个 Android 应用程序,它通过网络发送 2 种类型的对象,这些对象实现了 parcelable 接口(我们称它们为 objectA 和 objectB)作为字节数组。但在接收端,我需要知道包裹中是哪种类型的物品。 parcel.readValue()方法只有returns对象,所以在接收端不知道应该重新创建objectA还是objectB。如何才能做到这一点?包裹中是否有某种描述原始对象类型的元数据?

编辑:语言是 Java

编辑:添加了示例代码

        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
            }
        }

我想您可以访问 classes,这些可能是您收到的对象的可能类型。在 Java 中,您可以简单地使用 instanceof 运算符来检查您收到的对象是什么:

if (yourObject instanceof YourClass) {
  // Your code here
}

对于 Parcels,有一个 readValue 方法接受一个 class 加载器,用你的 classes class 加载器调用这个方法,它应该可以工作,例如:

Point pointFromParcel = (Point) parcel.readValue(Point.class.getClassLoader());

https://developer.android.com/reference/android/os/Parcel#readValue(java.lang.ClassLoader)

如果您不知道包装器 class 是什么对象,您可以创建一个包装器 class,其中包含一个 ObjectA 或一个 ObjectB 以及一个指示包装器当前包含哪个对象的字段。