Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a value back to an enum?

Tags:

java

enums

guava

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?

like image 362
Gili Avatar asked Apr 01 '11 15:04

Gili


People also ask

How do you map a String to an enum?

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.

Can we assign value to enum?

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.

What does valueOf return in enum?

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.


1 Answers

use:

static {
  for (SQLState sqlState : values()){
     codeToValue.put(sqlState.code, sqlState);
  }
}
like image 117
Puce Avatar answered Sep 23 '22 23:09

Puce