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

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

    In the modern Java implementations (at least JDK 6 through 10), the ObjectInputStream and ObjectOutputStream classes will only recognize readObject, readObjectNoData and writeObject methods if they are declared as private and NOT static.

    (I couldn't find this stated explicitly in any of the documentation, but the restriction is clearly implemented in the code.)

    So, irrespective of whether it is a good idea or not, FindBugs is correct in pointing out that a non-private readObject method is a bug. It won't be used.

    The only reason I want to make this method public is to make it final so that inheriting objects cannot fiddle with it.

    I don't think you should try to do that. Put a note in the class-level javadoc to say what you think that subclasses should and should not do. If someone chooses to implement a class ignoring that advice, it is their problem to deal with the consequences.

    The problem with trying to force other people to implement subclasses in a particular way is that they may have a use-case that requires them to do things differently ... for reasons that you are not in a position to understand. It is a better idea to leave future developers with the freedom to do what they want, and let them take responsibility for the consequences.

提交回复
热议问题