如何从其String值查找Java枚举? [英] How can I lookup a Java enum from its String value?

查看:125
本文介绍了如何从其String值查找Java枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从其字符串值(或可能的其他值)中查找枚举。我已经尝试了以下代码,但它不允许在初始化程序中静态。有没有一个简单的方法?

  public enum Verbosity {

简要,正常,

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);
}
};


解决方案

使用 valueOf 方法,它是为每个枚举自动创建的。

  Verbosity.valueOf(BRIEF)==功能。 

对于任意值,从$开始:

  public static Verbosity findByAbbr(String abbr){
for(Verbosity v:values()){
if(v.abbr()。equals(abbr)) {
return v;
}
}
返回null;
}

如果您的Profiler告诉您,只能继续前往Map实现。 p>

我知道它正在迭代所有的值,但只有3个枚举值,它几乎不值得任何其他的努力,事实上,除非你有很多价值,我不会打扰一张地图会足够快。


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);
    }
};

解决方案

Use the valueOf method which is automatically created for each Enum.

Verbosity.valueOf("BRIEF") == Verbosity.BRIEF

For arbitrary values start with:

public static Verbosity findByAbbr(String abbr){
    for(Verbosity v : values()){
        if( v.abbr().equals(abbr)){
            return v;
        }
    }
    return null;
}

Only move on later to Map implementation if your profiler tells you to.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆