如何从 String 值中查找 Java 枚举? [英] How can I lookup a Java enum from its String value?
问题描述
我想从其字符串值(或可能的任何其他值)中查找枚举.我已经尝试了以下代码,但它不允许在初始化程序中使用静态.有没有简单的方法?
I would like to lookup an enum from its string value (or possibly any other value). I've tried the following code but it doesn't allow static in initialisers. Is there a simple way?
public enum Verbosity {
BRIEF, NORMAL, FULL;
private static Map<String, Verbosity> stringMap = new HashMap<String, Verbosity>();
private Verbosity() {
stringMap.put(this.toString(), this);
}
public static Verbosity getVerbosity(String key) {
return stringMap.get(key);
}
};
推荐答案
使用为每个 Enum 自动创建的 valueOf
方法.
Use the valueOf
method which is automatically created for each Enum.
Verbosity.valueOf("BRIEF") == Verbosity.BRIEF
对于任意值以:
public static Verbosity findByAbbr(String abbr){
for(Verbosity v : values()){
if( v.abbr().equals(abbr)){
return v;
}
}
return null;
}
如果您的分析器告诉您,请稍后再转到 Map 实现.
Only move on later to Map implementation if your profiler tells you to.
我知道它正在迭代所有值,但只有 3 个枚举值几乎不值得做任何其他努力,事实上,除非您有很多值,否则我不会为 Map 烦恼它会足够快.
I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.
这篇关于如何从 String 值中查找 Java 枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!