Given an enum where each instance is associated with some value:
public enum SQLState
{
SUCCESSFUL_COMPLETION("00000"),
WARNING("01000");
private final String code;
SQLState(String code)
{
this.code = code;
}
}
How can I construct a Map for efficient reverse look-ups? I tried the following:
public enum SQLState
{
SUCCESSFUL_COMPLETION("00000"),
WARNING("01000");
private final String code;
private static final Map<String, SQLState> codeToValue = Maps.newHashMap();
SQLState(String code)
{
this.code = code;
codeToValue.put(code, this); // problematic line
}
}
but Java complains: Illegal reference to static field from initializer
. That is, the static Map is being initialized after all enum values so you cannot reference it from the constructor. Any ideas?
To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.
use:
static {
for (SQLState sqlState : values()){
codeToValue.put(sqlState.code, sqlState);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With