This answer is probably overkill. Maybe there's a badge for that. Anyway, it could be useful in a situation in which you have a lot of enumeration values and have to deal with a Strings as being the means by which another system sends information to you. That is exactly what I have (something north of 50), so I used this construct so that I could generate a mapping just once of the Strings reported by the db and the enums I used internally, and then not think about it after -- toString and fromString do all the work:
package com.stevej;
import com.google.common.collect.HashBiMap;
public enum TestEnum {
ALPHA("Alpha"), BETA("Beta"), GAMMA("Gamma");
private static HashBiMap<TestEnum, String> stringMapping = HashBiMap
.create(TestEnum.values().length);
private String stringValue = null;
TestEnum(String stringValue) {
this.stringValue = stringValue;
}
String getStringValue() {
return this.stringValue;
}
@Override
public String toString() {
return stringMapping.get(this);
}
public static TestEnum fromString(String string) {
return stringMapping.inverse().get(string);
}
static {
for (TestEnum e : TestEnum.values()) {
stringMapping.put(e, e.getStringValue());
}
}
}
Here's a quick test to show the data switching back and forth:
package com.stevej;
public class StackOverflowMain {
public static void main(String[] args) {
System.out.println(">> " + TestEnum.ALPHA);
System.out.println(">> " + TestEnum.BETA);
System.out.println(">> " + TestEnum.GAMMA);
TestEnum a = TestEnum.fromString("Alpha");
TestEnum b = TestEnum.fromString("Beta");
TestEnum c = TestEnum.fromString("Gamma");
System.out.println(">> " + a);
System.out.println(">> " + b);
System.out.println(">> " + c);
}
}
The output shows the use of the mixed case values instead of the uppercase, showing my strings are being used:
>> Alpha
>> Beta
>> Gamma
>> Alpha
>> Beta
>> Gamma
Note that I am using the Google Guava library so I can take advantage of the BiMap.