notserializableexception for an object whose class implements Serializable

淺唱寂寞╮ 提交于 2019-12-25 19:36:54

问题


I have this class

public class wordObject implements java.io.Serializable
    {
        String wordName;
        int occCount;
        int count;
        HashMap<Integer, Double> lineDict;
        int[] mat;

        public wordObject(String name,int num)
        {
            wordName = name;
            occCount=1;
            count = num;
            lineDict=new HashMap<Integer,Double>(lineC);
            mat = new int[lineC];

        }

    }

But when I try to write an instance of the class to the disk using a piece of code as given below

public static writeObj(WordObject obj)
    FileOutputStream f_out = new FileOutputStream(loc);

            // Write object with ObjectOutputStream
            ObjectOutputStream obj_out = new ObjectOutputStream (f_out);

            // Write object out to disk,obj is instance of wordObject
            obj_out.writeObject ( obj );

I get this error

Exception in thread "main" java.io.NotSerializableException: searchTAemd
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)

Any help will be most welcome.

EDIT: I have checked that HashMap already implements serializable.


回答1:


Since wordObject is an inner class, and an inner class always holds an implicit reference to its outer class, you cannot serialize an inner class unless the outer class is also serializable. Actually it's not even recommended to try;

From the serialization specification;

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged for several reasons. Because inner classes declared in non-static contexts contain implicit non-transient references to enclosing class instances, serializing such an inner class instance will result in serialization of its associated outer class instance as well.




回答2:


When doing serialization, all objects that your object can reach (ie its member variables and the members of its members etc etc) must be serializable, or you get this exception. This is common problem with object serialization



来源:https://stackoverflow.com/questions/9998910/notserializableexception-for-an-object-whose-class-implements-serializable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!