Question
How can I look up a Java enum by its String value?
public enum Verbosity {
BRIEF, NORMAL, FULL;
private static Map<String, Verbosity> stringMap = new HashMap<>();
static {
for (Verbosity verbosity : Verbosity.values()) {
stringMap.put(verbosity.name(), verbosity);
}
}
public static Verbosity getVerbosity(String key) {
return stringMap.get(key);
}
}
Answer
Retrieving a Java enum using its String representation can be accomplished by utilizing a static map to store and quickly look up enum instances.
public enum Verbosity {
BRIEF, NORMAL, FULL;
private static Map<String, Verbosity> stringMap = new HashMap<>();
static {
for (Verbosity verbosity : Verbosity.values()) {
stringMap.put(verbosity.name(), verbosity);
}
}
public static Verbosity getVerbosity(String key) {
return stringMap.get(key);
}
}
Causes
- The code provided uses an instance initializer, which is not suitable because it tries to use static context within an instance method.
- Static initialization blocks must be used to initialize static members correctly.
Solutions
- Use a static initializer block to populate the map when the enum class is loaded.
- Replace `this.toString()` with `this.name()` which is more common for enum constants.
Common Mistakes
Mistake: Using `this.toString()` instead of `this.name()` in the enum context.
Solution: Use `this.name()` to get the string representation of the enum constant.
Mistake: Not initializing the static map properly in the enum.
Solution: Utilize a static block to populate the `stringMap`.
Helpers
- Java enum
- lookup enum by string
- Java get enum from string
- enum static initializer
- Java enums best practices