tags:

views:

185

answers:

3

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(){};
}
+4  A: 

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.

Hank Gay
Just implementing readResolve wont fix it.
Tom Hawtin - tackline
Which is why I told jjujuma to go read the appropriate item from Effective Java.
Hank Gay
+2  A: 

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
}
Hannes de Jager
...which doesn't work securely, because the instance can be nabbed before readResolve.
Tom Hawtin - tackline
Oh I see someone already mentioned Joshua's book. Highly recommended reading btw.
Hannes de Jager
Tom, can you shed a bit more light as to why?
Hannes de Jager
+1  A: 

This link is an example from sun that works similarly to the solution presented in Effective Java as suggested by other posters.

Rich Kroll