Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 made public?

like image 939
Jérôme Verstrynge Avatar asked Jan 25 '26 06:01

Jérôme Verstrynge


1 Answers

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!

like image 107
shrini1000 Avatar answered Jan 27 '26 19:01

shrini1000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!