如何根据一个值找到一个枚举? [英] How to find an enum according to a value?

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

问题描述

我正在使用一个看起来像这样的(旧版,不可更改)枚举:

I'm working with a (legacy, not changeable) enum that looks like this:

enum MsgEnum {
   private int number;
   private int msg;

   MSG_OK("OK", 0);
   MSG_NOK("NOK, 1);
   //lots of other messages

   private MsgEnum(String msg, int number) {
      this.msg = msg;
      this.number = number;
   }
}

如果我有 number ,如何最好地找出哪个 MsgEnum 与该数字匹配(假设它们是唯一的)?

If I have the number, how could I best find out which MsgEnum matches the number (assuming they are unique)?

除了以下内容之外,还有其他更好的方法吗?

Is there any better way apart from the following?

class MyEnumHelper() {

    public static MsgEnum MsgEnumfromNumber(int number) {
        for (MsgEnum m : MsgEnum.values()) {
            if (m.getNumber() == number) {
                return m;
            }
        }
        return null;
    }
}

推荐答案

您可以在Helper中声明一个静态Map,并使用静态方法getMsgEnumFromInteger(int)对其进行访问.像这样的东西:

You can declare a static Map in your Helper and access it using a static method getMsgEnumFromInteger(int). Something like :

private static final Map<Integer, MsgEnum> INT_TO_ENUM = new HashMap<Integer, MsgEnum>();

static {
    for (MsgEnum msgE : MsgEnum.values) {
        INT_TO_ENUM.put(msgE.getNumber(), msgE);
    }
}

public static MsgEnum getByInt(int number) {
    return INT_TO_ENUM.get(number);
}

(很抱歉,如果有错误,^^时还没有Java env)

(sorry if there are errors, it don't have a Java env at the moment ^^ )

这篇关于如何根据一个值找到一个枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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