Java – how do I map values to enumerations?
•
Java
Given an enumeration, each instance is associated with some values:
public enum sqlState { SUCCESSFUL_COMPLETION("00000"),WARNING("01000"); private final String code; sqlState(String code) { this.code = code; } }
How to build an effective reverse lookup map? I have 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 that it illegally references static fields from the initializer That is, a static map is initialized after all enumerated values, so you cannot reference it from the constructor Any ideas?
Solution
use:
static { for (sqlState sqlState : values()){ codeToValue.put(sqlState.code,sqlState); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码