Check if enum exists in Java

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

Edit: 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.

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


If I need to do this, I sometimes build a Set<String> of the names, or even my own Map<String,MyEnum> - then you can just check that.

A couple of points worth noting:

  • Populate any such static collection in a static initializer. Don't use a variable initializer and then rely on it having been executed when the enum constructor runs - it won't have been! (The enum constructors are the first things to be executed, before the static initializer.)
  • Try to avoid using values() frequently - it has to create and populate a new array each time. To iterate over all elements, use EnumSet.allOf which is much more efficient for enums without a large number of elements.
  • Sample code:

    import java.util.*;
    
    enum SampleEnum {
        Foo,
        Bar;
    
        private static final Map<String, SampleEnum> nameToValueMap =
            new HashMap<String, SampleEnum>();
    
        static {
            for (SampleEnum value : EnumSet.allOf(SampleEnum.class)) {
                nameToValueMap.put(value.name(), value);
            }
        }
    
        public static SampleEnum forName(String name) {
            return nameToValueMap.get(name);
        }
    }
    
    public class Test {
        public static void main(String [] args)
            throws Exception { // Just for simplicity!
            System.out.println(SampleEnum.forName("Foo"));
            System.out.println(SampleEnum.forName("Bar"));
            System.out.println(SampleEnum.forName("Baz"));
        }
    }
    

    Of course, if you only have a few names this is probably overkill - an O(n) solution often wins over an O(1) solution when n is small enough. Here's another approach:

    import java.util.*;
    
    enum SampleEnum {
        Foo,
        Bar;
    
        // We know we'll never mutate this, so we can keep
        // a local copy.
        private static final SampleEnum[] copyOfValues = values();
    
        public static SampleEnum forName(String name) {
            for (SampleEnum value : copyOfValues) {
                if (value.name().equals(name)) {
                    return value;
                }
            }
            return null;
        }
    }
    
    public class Test {
        public static void main(String [] args)
            throws Exception { // Just for simplicity!
            System.out.println(SampleEnum.forName("Foo"));
            System.out.println(SampleEnum.forName("Bar"));
            System.out.println(SampleEnum.forName("Baz"));
        }
    }
    

    One of my favorite lib: Apache Commons.

    The EnumUtils can do that easily.

    Here is a sample code to validate an Enum:

    MyEnum strTypeEnum = null;
    
    // test if String str is compatible with the enum 
    if( EnumUtils.isValidEnum(MyEnum.class, str) ){
        strTypeEnum = MyEnum.valueOf(str);
    }
    
    链接地址: http://www.djcxy.com/p/6488.html

    上一篇: 通过字符串值查找Java枚举

    下一篇: 检查Java中是否存在枚举