反序列化集合时不安全的通用转换

Ste*_*ker 6 java generics serialization casting

public Configuration(Node node, File file) {
    HashMap<String, String> conf = (HashMap<String, String>) SerializationUtils.deserialize(new FileInputStream(file));
}
Run Code Online (Sandbox Code Playgroud)

我理解为什么这会给出不安全的演员警告,但是安全地做到这一点的最佳/可接受方式是什么?有什么好办法吗?

Tom*_*ine 2

仅使用 Java 语言无法以完全类型安全的方式处理这种情况。

因为这是必须重复完成的事情,并且您无法真正绕过它,所以我建议使用流派方法来读取和转换通用对象:

@SuppressWarnings("unchecked")
public static <T> T readObject(
    ObjectInputStream in
) throws IOException, ClassNotFoundException {
    return (T)in.readObject();
}
Run Code Online (Sandbox Code Playgroud)

但是,我建议您通常不要使用这样的方法来抑制有效警告。