【问题标题】:Need help to understand deserialization with ArrayList in Java需要帮助来理解 Java 中使用 ArrayList 的反序列化
【发布时间】:2015-09-05 11:20:18
【问题描述】:

我想将 ArrayList 写入文件,然后再次读取。该列表将保存 Integer 对象。序列化似乎工作正常,但我在反序列化时遇到了麻烦。更具体地说,我无法正确选择。

序列化:

ObjectOutputStream ou =
    new ObjectOutputStream(new FileOutputStream(new File("load.dat")));

ArrayList<Integer> ouList = new ArrayList<>();
ou.writeObject(ouList);
ou.close();

derserization:

ObjectInputStream in =
    new ObjectInputStream(new FileInputStrean("load.dat"));
ArrayList<Integer> inList = (ArrayList<Integer>)(in.readObject();
in.close();

当我编译时,我会收到未经检查且不安全的警告。我用 Xclint:unchecked 重新编译并收到以下消息:

warning: [unchecked] unchecked cast
    ArrayList<Integer> inList = (ArrayList<Integer>)(in.readObject());
                                                    ^
  required: ArrayList<Integer>
  found:    Object

我觉得这有点令人困惑:强制转换不应该将对象转换为数组列表吗?为什么它需要 ArrayList 当我将它投射到它时?提前感谢您的帮助。

【问题讨论】:

  • 删除 in.readObject() 周围的括号会发生什么。试试这个 ArrayList inList = (ArrayList )in.readObject();
  • 从 Object 转换泛型会导致未经检查的转换,删除泛型可解决未经检查的警告,但如果您需要 rawtype 忽略警告,请按照建议使用 try/catch

标签: java serialization arraylist casting deserialization


【解决方案1】:

它告诉您编译器无法向您保证强制转换在运行时会成功 - 它可能会产生 ClassCastException

通常您可以使用 instanceof 检查类型以防止出现此警告,例如:

if (x instanceof ArrayList) {
    ArrayList y = (ArrayList) x; // No warning here 
}

很遗憾instanceof 无法在运行时检查泛型参数,因此您将无法安全地执行此操作。您所能做的就是取消警告。

但是,如果您真的想确定集合的类型,那么您可以通过以下方式更改您的代码:

public class ArrayListOfIntegers extends ArrayList<Integer> {}

...

// writing:
ArrayListOfIntegers ouList = new ArrayListOfIntegers();
...
// reading:
ArrayListOfIntegers inList;
Object readData = in.readObject();
if (readData instanceof ArrayListOfIntegers) {
    inList = (ArrayListOfIntegers) readData;
} else {
    throw new RuntimeException("...");
}

【讨论】:

    【解决方案2】:

    由于您收到未经检查/不安全的警告,我建议将它们放在 try/catch 块中。

    这是一个相对简单的教程,完全符合您的要求:http://beginnersbook.com/2013/12/how-to-serialize-arraylist-in-java/

    【讨论】:

    • 本教程也会抛出相同的警告,只要捕获到异常,就挂起这样的不安全操作是否很常见?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多