01: import java.io.ObjectStreamException;
02: import java.io.Serializable;
03: import java.lang.reflect.Field;
04: 
05: /**
06:    This class is a superclass for enumerated types that
07:    can be serialized. Subclass like this:
08:    <pre>
09:    public class MyEnumeration extends SerializableEnumeration
10:    {
11:       private MyEnumeration() {}
12:       public static final MyEnumeration FOO = new MyEnumeration();
13:       public static final MyEnumeration BAR = new MyEnumeration();
14:       . . .
15:    }
16:    </pre>
17:    This defines instances <code>MyEnumeration.FOO</code> and
18:    <code>MyEnumeration.BAR</code> that are guaranteed to
19:    be preserved through serialization and deserialization.
20:    Conveniently, the toString method yields the name (such
21:    as <code>&quot;FOO&quot;<code>).
22: */
23: public class SerializableEnumeration implements Serializable
24: {
25:    protected Object writeReplace() throws ObjectStreamException
26:    {
27:       if (name == null) toString();
28:       if (name == null)
29:          throw new ObjectStreamException("No matching field") {};
30:       return this;
31:    }
32: 
33:    public String toString()
34:    {
35:       if (name != null) return getClass().getName() + "." + name;
36:       try
37:       {
38:          Field[] fields = getClass().getFields();
39:          for (int i = 0; i < fields.length; i++)
40:          {
41:             if (fields[i].get(this) == this)
42:             {
43:                name = fields[i].getName();
44:                return toString();
45:             }
46:          }
47:       }
48:       catch (IllegalAccessException ex) {}
49:       return super.toString();
50:    }
51: 
52:    protected Object readResolve() throws ObjectStreamException
53:    {
54:       try
55:       {
56:          return getClass().getField(name).get(null);
57:       }
58:       catch (IllegalAccessException ex) {}
59:       catch (NoSuchFieldException ex) {}
60:       throw new ObjectStreamException("No matching field") {};
61:    }
62: 
63:    private String name;
64: }