我正在制作一個 Android 應用程序,它通過網絡以字節數組的形式發送 2 種類型的對象,這些對象實現了 Parcelable 接口(我們稱它們為 objectA 和 objectB)。但在接收端,我需要知道包裹中到達的是哪種類型的物體。Parcel.readValue() 方法僅返回 Object,因此在接收端我不知道應該重新創建 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 } }
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
我想您可以訪問可能是您收到的對象的可能類型的類。在Java中,您可以簡單地使用instanceof運算符來檢查您收到的對象是什么:
if (yourObject instanceof YourClass) {
// Your code here
}
對于 Parcels,有一個接受類加載器的 readValue 方法,使用您的類加載器調用此方法,它應該可以工作,例如:
Point pointFromParcel = (Point) parcel.readValue(Point.class.getClassLoader());
https://developer.android.com/reference/android/os/Parcel#readValue(java.lang.ClassLoader)
如果您不知道包裝器類將是什么對象,您可以創建一個包裝器類,其中包含 ObjectA 或 ObjectB 以及一個指示包裝器當前持有哪個對象的字段。
添加回答
舉報
0/150
提交
取消