简体   繁体   English

如何通过值查找枚举

[英]How to find a enumeration by its value

public enum Foo {
   one ("one"), two ("two")
}

How to find a enumeration by its value (say Foo.getFoo("two") ) should return Foo.two . 如何通过其值查找枚举(例如Foo.getFoo("two") )应返回Foo.two

Each enum has a valueOf(String) method that looks up an instance given the name. 每个enum都有一个valueOf(String)方法,该方法查找具有给定名称的实例。

Foo.valueOf("one") == Foo.one

This is based on the name of the enum value. 这基于枚举值的名称。 There is no concept of value as such for enums -- only names and ordinals. 枚举没有这样的价值概念,只有名称和序数。

You have some options... 您有一些选择...

Know the enum, want to look up by name 知道枚举,想按名称查找

If you know the exact enum type and its name, as others have pointed out, you can use it directly: 如其他人所指出的,如果您知道确切的枚举类型及其名称,则可以直接使用它:

Foo myFoo = Foo.valueOf("one");

Keep in mind that the string has to match the enum name exactly, including case. 请记住,字符串必须与枚举名称完全匹配,包括大小写。 Enum values are usually all-caps, so if you're looking up by some String s , it's often a good idea to do Foo.valueOf(s.toUpperCase()) . 枚举值通常是全大写的,因此,如果您要查找一些String s ,则通常最好执行Foo.valueOf(s.toUpperCase())

Have the enum's Class, want to look up by name 有枚举的类,想按名称查找

If you don't have that type, but you have a class representing the enum type, you can use the static method Enum.valueOf(Class<T>, String) to get the enum for its name: 如果没有该类型,但是有一个表示枚举类型的类,则可以使用静态方法Enum.valueOf(Class<T>, String)来获取其名称的枚举:

Class<T> myEnumClass = whatever();
T myEnum = Enum.valueOf(myEnumClass, "one");

As above, the string is case sensitive. 如上所述,字符串区分大小写。

Want to look up by some non-name attribute 要通过一些非名称属性查找

If you want to look up the enum by some other (presumably unique) value, one approach would be to loop over the enum values. 如果要按其他(可能唯一)的值查找枚举,则一种方法是遍历枚举值。 You can get them either from Foo.values() , or, if you just have a Class<T> , you can use the instance method Class.getEnumConstants() : 您可以从Foo.values()获得它们,或者,如果您只有Class<T> ,则可以使用实例方法Class.getEnumConstants()

T[] values = myEnumClass.getEnumConstants();
for (T value : values) ...

same, but potentially faster 一样,但可能更快

If you need to do this often, and speed is a concern, it may be useful to pre-load these into a map (but see below for caveats): 如果您需要经常执行此操作,而速度是一个问题,那么将它们预加载到地图中可能会很有用(但请注意以下内容):

Map<EnumVal, Foo> valuesToEnum = new HashMap<EnumVal, Foo>();
for (Foo foo : Foo.values()) {
    EnumVal val = foo.getValue();
    Foo oldFoo = valuesToEnum.put(val, foo);
    assert oldFoo == null : "multiple Foos have a value " + val;
        // ^^^ this means we can't meaningfully look up by EnumVals.
}
// now you can do something like
EnumVal lookupBy = whatever2();
Foo foo = valuesToEnum.get(lookupBy);
if (foo == null)
    throw new IllegalArgumentException("no Foo has the value " + lookupBy);

Note that this requires calculating the EnumVal 's hash, if it's not pre-computed, and then a couple lookups. 请注意,这需要计算EnumVal的哈希值(如果未预先计算),然后进行几次查找。 If you have a lot of values in the enum, this lookup could be worth it. 如果枚举中包含很多值,则此查找值得。 Otherwise, a loop over a handful of items is likely to be about as fast, plus or minus -- and either way, it'll be negligible. 否则,在少数几个项目上循环可能大约一样快(正负),而且无论哪种方式,都可以忽略不计。

特别是在您的情况下, Foo.valueOf(String)可以做到。

The valueOf(String) only works on the declared name s of Enum . valueOf(String)仅适用于Enum的声明name If you want to find an enum by some custom value, the best way is to provide a find method: 如果要通过某个自定义值查找enum ,最好的方法是提供一个find方法:

public static Foo fromValue(String value) {
    for (Foo foo : Foo.values()) {
        if (foo.value.equals(value)) {
            return foo;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM