![](/img/trans.png)
[英]Implementing Serializable without providing writeObject / readObject method
[英]Class implementing Serializable cannot readObject
我正在嘗試使用以下序列化對:
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
if (mPair != null) {
String first = mPair.first;
String second = mPair.second;
mPair = null;
try {
out.writeChars(first);
out.writeChars("\n");
out.writeChars(second);
} catch (Exception e) {
}
}
}
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
try {
String first = in.readLine();
String second = in.readLine();
mPair = new Pair<String, String>(first, second);
} catch (EOFException e) {
mPair = new Pair<String, String>("", "");
}
}
我調試了writeObject
被正確調用我有3個自定義類對象,當我的應用程序離開屏幕時,但當我回到應用程序時, readObject
永遠不會被調用。
原來這個簡單的解決方案似乎有效:
public class SerializableStringPair extends Pair<String, String> implements
Serializable {
private static final long serialVersionUID = 1L;
public SerializableStringPair(String first, String second) {
super(first, second);
}
}
另外兩件事
只需兩個字符串,就不需要特殊的代碼來序列化或反序列化類。 這是標准行為。 只需像你那樣聲明implements Serializable
,就是這樣。
您的問題中的代碼包含錯誤:第二個字符串最后沒有換行符。 使用readLine
讀取時,序列化必須混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.