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

后端 未结 5 2061
太阳男子
太阳男子 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:56

    About readObject()/writeObject() being private, here's the deal: if your class Bar extends some class Foo; Foo also implements readObject()/writeObject() and Bar also implements readObject()/writeObject().

    Now, when a Bar object is serialized or deserialized, JVM needs to call readObject()/writeObject() for both Foo and Bar automatically (i.e. without you needing to call these super class methods explicitly). However, if these methods are anything but private, it becomes method overriding, and JVM can no longer call the super class methods on the sub class object.

    Hence they must be private!

提交回复
热议问题