private Class readObject (ObjectInput in, Class objectclass){
try {
Object o = in.readObject();
if (o instanceof objectclass) {
return (objectclass)o;
}
} catch (Exception e) {
}
在我的課堂我打電話這個功能:
ObjectInput in = (..)
Type1 type = readObject (in, Type1.class);
(do something with type)
while(true){
Type2 type2 = readObject (in, Type2.class);
(do something with type2)
基本上的readObject應該返回的類,我作爲參數,如果這是Object o的正確類型。你可以這樣想,我有我正在閱讀的Type1,Type2和Type3對象,但是如果我遇到Type3,我什麼都不做。
我寫的這段代碼無法正常工作。例如,
Type1 type = readObject (in, Type1.class);
給我警告「無法從Class轉換爲Type1」。
你有三個不同的等級叫' Class','Type1'和'Type2'? – Gendarme
Type1和Type2是類別yes。 「班級」是我嘗試返回班級的方式。我也試過類>和類,似乎沒有幫助 –
hokosha
由於返回類型必須是'Type1'或'Type2'的實例,但您返回'Class'的實例 – Clayn