Enumerations in Java

Christoph Karl Walter Grein

Java programmers have always missed the ease of constructing enumeration types like Ada's

The Enumeration Factory provides a simple to use model to construct Java classes representing such enumerations together with all operations that are available in Ada (like the order functions "<" and "<=" or the attributes 'Image, 'Pos, 'Succ, just to name a few).

This class has been introduced into the Apache project
Package org.apache.cocoon.util.EnumerationFactory.

There seems however to be a basic problem with this method, which Dr. Michael Paus informed me about via e-mail on Mon, 17 Dec 2001. Here is an abstract of his letter (my translation):

... While experimenting with your Java class EnumerationFactory, I found a severe problem. That the tests you provided in the class Test_EnumerationExample work is a pure coincidence, stipulated by the sequence in which you perform the tests. I inserted in the main program at the beginning the following tests:
    if (EnumerationExample.getObject("BLUE") == null) {
      println ("TEST FAILED: EnumerationExample.getObject(\"BLUE\") == null");
    EnumerationExample test =
    if (test == null) {
      println ("TEST FAILED: test == null");
    if (EnumerationExample.getVal(2) == null) {
      println ("TEST FAILED: EnumerationExample.getVal(2) == null");
The result is:
TEST FAILED: EnumerationExample.getObject("BLUE") == null
TEST FAILED: test == null
java.lang.ArrayIndexOutOfBoundsException: 2 >= 0
  at java.util.Vector.elementAt(Vector.java:417)
  at cgrein.enumerations.EnumerationFactory.getVal(EnumerationFactory.java)
  at Test_EnumerationExample.main(Test_EnumerationExample.java)
Exception in thread "main" Process Exit...
The reason of this failure can be found in the nature of static methods. For example, the static method getObject of the class EnumerationFactory can also be called from the derived example class, this call however does not lead to an initialisation (elaboration in Ada speak) of this class. This means all calls fail if other than in your test examples something explicitly forcing an initialisation is not called before (like e.g. EnumerationExample enum = EnumerationExample.RED;).

... Perhaps there is a workaround for this problem. Unfortunately nothing has come to my mind yet.

By the way, my tests were performed under Windows 98 with SUN JDK 1.3.1_01...

Now also I cannot provide a solution, especially since I currently do not use Java and am not very used to this language. So any solutions are welcome.

Last software update: 18 December 2001

Bug reports and proposals for improvements are welcome.

(*) The code is shown colorized. This was created by an application of the Ada and Java Lexer.