检查Java中是否存在枚举 [英] Check if enum exists in Java

查看:2511
本文介绍了检查Java中是否存在枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有反正通过比较它与给定的字符串来检查枚举是否存在?我似乎找不到任何这样的功能。我可以尝试使用 valueOf 方法并捕获异常,但我被告知捕获运行时异常不是好的做法。任何人都有任何想法?

Is there anyway to check if an enum exists by comparing it to a given string? I can't seem to find any such function. I could just try to use the valueOf method and catch an exception but I'v been taught that catching runtime exceptions is not good practice. Anybody have any ideas?

推荐答案

我不认为有一个内置的方法,你可以使用这样的:

I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:

public static MyEnum asMyEnum(String str) {
    for (MyEnum me : MyEnum.values()) {
        if (me.name().equalsIgnoreCase(str))
            return me;
    }
    return null;
}

编辑:Jon Skeet指出, values()通过在每次调用时克隆一个专用后备数组。如果性能很重要,您可能只需调用 values()一次,缓存数组,然后迭代。

As Jon Skeet notes, values() works by cloning a private backing array every time it is called. If performance is critical, you may want to call values() only once, cache the array, and iterate through that.

此外,如果你的枚举有大量的值,Jon Skeet的map选择可能会比任何数组迭代更好。

Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.

这篇关于检查Java中是否存在枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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