How to serialize static data members of a Java class?

后端 未结 9 1890
孤城傲影
孤城傲影 2020-11-27 17:30

When we serialize objects, static members are not serialized, but if we need to do so, is there any way out?

9条回答
  •  再見小時候
    2020-11-27 18:06

    Good answers and comments--don't do it. But how?

    Chances are you would be best off creating an object to hold all your "Statics". That object should probably have any static methods from your class as well.

    Every instance of your class can hold this other class--or if you really have to you can make it a singleton that any member can access.

    After you do this refactor, you will find that it should have been done this way all along. You may even find that some of your previous design constraints that were bothering you at a subconsicionce level have vanished.

    You'll probably find that this solution also solves other Serialization problems you hadn't even noticed yet.

提交回复
热议问题