0

我正在尝试使用以下方法对 Pair 进行序列化:

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从来没有被调用过。

4

2 回答 2

1

额外的两件事

  • 您不需要特殊的代码来序列化或反序列化只有两个字符串的类。这是标准行为。就像implements Serializable 你一样声明,就是这样。

  • 您问题中的代码包含错误:第二个字符串末尾没有换行符。使用 阅读时readLine,序列化必须混淆。

于 2013-10-24T13:11:18.963 回答
1

事实证明,这个简单的解决方案似乎有效:

public class SerializableStringPair extends Pair<String, String> implements
    Serializable {

    private static final long serialVersionUID = 1L;

    public SerializableStringPair(String first, String second) {
        super(first, second);
    }
}
于 2013-10-24T12:28:50.960 回答