![](/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.