How to guarantee Java instance control (without enum) in world of serialization?

前端 未结 2 1930
萌比男神i
萌比男神i 2021-01-19 09:25

In a world before Java 1.5 (so no enum) and with my object being serialized, how can I enforce proper instance control? I\'m talking about a class like this, w

相关标签:
2条回答
  • 2021-01-19 10:05

    You should really check out Effective Java. The chapter on Singleton addresses this somewhat, and there is a chapter on the Typesafe Enum pattern that was definitely an influence on the way enum was implemented.

    The short answer is you have to implement readResolve.

    0 讨论(0)
  • 2021-01-19 10:16

    If I understand you correctly then what you are looking for is to take Joshua Bloch' advice and implement the readResolve method to return one of your constant instances.

    private Object readResolve() throws ObjectStreamException {
      return PRIVATE_VALUES[ordinal];  // The list holding all the constant instances
    }
    
    0 讨论(0)
提交回复
热议问题