Sunday, January 10, 2010

Java enum and Static Variables

I've been moving back into the world of Java after some time with Ruby...surprisingly (to me anyway) Java enums don't have access to static variables within the enum in the enum constructor. For example, this will fail to compile with an illegal forward reference when attempting to use the static constant:

public enum Foo {
BAR(DEFAULT_VALUE), BAZ(44);
private static final int DEFAULT_VALUE = 42;
private int value;
Foo(int value) {
this.value = value;
}
/*
Foo.java:3: illegal forward reference
BAR(DEFAULT_VALUE), BAZ(44);
^
1 error
*/
}
view raw gistfile1.java hosted with ❤ by GitHub


I haven't found a work around for this that I am comfortable with. Defining the static constants elsewhere seems quite ugly.

The same problem occurs if you want to set up a static cache during construction as well. This can be worked around with a static initializer:

import java.util.HashMap;
import java.util.Map;
public enum Foo {
BAR(""), BAZ("");
private static final Map<String, Foo> fooMap = new HashMap<String, Foo>();
static {
for (Foo foo : values()) {
fooMap.put(foo.getAlias(), foo);
}
}
private String alias;
Foo(String alias) {
this.alias = alias;
}
public String getAlias() {
return alias;
}
public static Foo fromAlias(String alias) {
return fooMap.get(alias);
}
}
view raw gistfile2.java hosted with ❤ by GitHub