Can I add and remove elements of enumeration at runtime in Java

Solution 1:

No, enums are supposed to be a complete static enumeration.

At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.

In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface for the interface and an enum that implements that interface for the standard values. Of course, you lose the ability to switch when you only have a reference to the interface.

Solution 2:

Behind the curtain, enums are POJOs with a private constructor and a bunch of public static final values of the enum's type (see here for an example). In fact, up until Java5, it was considered best-practice to build your own enumeration this way, and Java5 introduced the enum keyword as a shorthand. See the source for Enum<T> to learn more.

So it should be no problem to write your own 'TypeSafeEnum' with a public static final array of constants, that are read by the constructor or passed to it.

Also, do yourself a favor and override equals, hashCode and toString, and if possible create a values method

The question is how to use such a dynamic enumeration... you can't read the value "PI=3.14" from a file to create enum MathConstants and then go ahead and use MathConstants.PI wherever you want...

Solution 3:

I needed to do something like this (for unit testing purposes), and I came across this - the EnumBuster: http://www.javaspecialists.eu/archive/Issue161.html

It allows enum values to be added, removed and restored.

Edit: I've only just started using this, and found that there's some slight changes needed for java 1.5, which I'm currently stuck with:

  • Add array copyOf static helper methods (e.g. take these 1.6 versions: http://www.docjar.com/html/api/java/util/Arrays.java.html)
  • Change EnumBuster.undoStack to a Stack<Memento>
    • In undo(), change undoStack.poll() to undoStack.isEmpty() ? null : undoStack.pop();
  • The string VALUES_FIELD needs to be "ENUM$VALUES" for the java 1.5 enums I've tried so far