jjujuma
jjujuma

Reputation: 22775

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

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, where, as far as I can tell, I'm not sure that instance0 and instance1 will always be the only instances.

import java.io.Serializable;

public final class Thing implements Serializable {

    private static final long serialVersionUID = 1L;

    public static final Thing instance0 = new Thing();
    public static final Thing instance1 = new Thing();

    private Thing(){};
}

Upvotes: 4

Views: 1499

Answers (2)

Hannes de Jager
Hannes de Jager

Reputation: 2923

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
}

Upvotes: 2

Hank Gay
Hank Gay

Reputation: 71939

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.

Upvotes: 4

Related Questions