This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ | |
} |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |