在Java

时间:2016-10-11 14:23:15

标签: java serialization hashmap

我正在尝试序列化HashMap<String, Object>类型的对象。但是,我在运行时得到NotSerializableException。这是我用于序列化的代码

public void WriteModel(String modelFile, HashMap<String, Object> o) {
    try {
        ObjectOutputStream os = new ObjectOutputStream (new FileOutputStream (modelFile));
        os.writeObject(o);
        os.close();
    }
    catch (Exception e) {
        System.out.println ("Error in saving model " + modelFile + ": " + e);
        e.printStackTrace();
    }
}

HashMap具有int作为值或具有以下类型的对象

public class suggestMenu implements Serializable {
    private static final long serialVersionUID = -8558253517294665710L;
    public List<Integer> suggestions = new ArrayList<Integer>();
    public int freq = 0; 
}

所以基本上HashMap中包含的所有对象都是可序列化的。 我做错了什么?它是否与HashMap包含多个类型的事实有关? 鉴于几乎不可能改变其结构,可能的序列化方法是什么?

这是错误的完整堆栈跟踪

Error in saving model /home/ritesh/Documents/spell-checker/dict_ser.ser: java.io.NotSerializableException: spell.SpellCheckTrainer
java.io.NotSerializableException: spell.SpellCheckTrainer
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at java.util.HashMap.writeObject(HashMap.java:1129)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
at spell.SpellCheckTrainer.WriteModel(SpellCheckTrainer.java:254)
at spell.SpellCheckTrainer.CreateDictionary(SpellCheckTrainer.java:246)
at spell.SpellCheckTrainer.main(SpellCheckTrainer.java:55)

1 个答案:

答案 0 :(得分:0)

HashMap可以序列化,但是您将Object作为值。这些对象可能像您的SpellCheckTrainer类一样序列化。使该类可序列化可能会很好。注意:Sonarqube代码分析仍会将其标记为squid:S1948的严​​重问题