FindBugs wants readObject(…) to be private for serialization, why?

后端 未结 5 1998
太阳男子
太阳男子 2021-01-20 08:59

I am running findbugs on some code and it says the readObject(...) method must be private to be invoked for serialization/unserialization? Why? What is the problem if it is

5条回答
  •  一向
    一向 (楼主)
    2021-01-20 09:40

    In order for your method to be called by objectInputStream.readObject(), you must declare it private:

    private void readObject(ObjectInputStream objectInputStream)
    

    If you do not, your method will not be called (put a break point in there to prove this). Your code may appear to work but that is because the default serialization is being used.

    You might be wanting to make this protected to allow for subclassing but this is not needed. The serialization process automatically calls the readObject of the base class prior to calling the readObject of the concrete class. This happens even if the concrete class does not make a call to:

    objectInputStream.defaultReadObject();
    

    ...contrary to other posts I have read on the web. The same applies to the writeObject methods as well.

提交回复
热议问题