将字符串转换为相应的枚举值

123
5个回答

261

希望你意识到,java.util.Enumeration和Java 1.5的枚举类型是不同的。

你可以使用YourEnum.valueOf("String")来获取相应的枚举类型。

因此,如果你的枚举类型定义如下:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY
}
你可以这样做:
String day = "SUNDAY";

Day dayEnum = Day.valueOf(day);

是的,谢谢。我刚看到这个:http://download.oracle.com/javase/1,5.0/docs/api/java/lang/Enum.html - Ankur
4
谢谢@adarshr,但有个问题。如果该值不属于该组怎么办?例如:Day.valueOf("randomValue"); - Artanis Zeratul
3
@ArtanisZeratul - 如果提供的值不在枚举中,你将会得到一个 IllegalArgumentException。 - Sidharth Ramesh

20

假设您使用的是Java 5枚举(这不是很确定,因为您提到旧的Enumeration类),则可以使用java.lang.Enum子类的valueOf方法:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

9

使用每个enum定义的静态方法valueOf(String)

例如,如果您有enum MyEnum,则可以使用MyEnum.valueOf("foo")


6

我可能过度工程化了自己的解决方案,没有意识到Type.valueOf("enum string")实际上存在。

我猜它提供了更细粒度的控制,但我不确定它是否真的有必要。

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

我猜你想把 IllegalArgumentException 替换为 RuntimeException(或者任何你想要抛出的异常),这样有可能可以简化代码。

0
关于使用valueOf(string)的其他回答是正确的,但我想补充一点,你应该保护你的代码,以防止传递无效的字符串。虽然今天你的代码可能只传递与有效枚举值相对应的字符串,但未来枚举或其他部分的代码(或其他人编写的代码)的更改可能会破坏这个假设。
这对于像为类的枚举成员变量编写setter这样的情况非常重要。你的类和它的setter应该保护自己。 JavaDocs for Enum显示,这可能会引发异常(IllegalArgumentExceptionNullPointerException)。你应该通用或具体地处理这些异常。JavaDocs还显示,这个函数不喜欢“多余的空格”...所以考虑使用trim()。
我可能会像这样通用地处理异常:
Enum BestEnumEver {OPTION_A, OPTION_B, OPTION_C}

// ... elsewhere in your code ...
// How confident are you that stringVar will have an acceptable value?
// How confident are you that the existing enum options will not need to change?
BestEnumEver enumValue;
try {
    // Consider using trim to eliminate extraneous whitespace
    enumValue = BestEnumEver.valueOf(stringVar.trim());
} catch (Exception e) {
    // handle the situation here. Here are a couple of ideas.
    // Apply null and expect the using code to detect.
    enumValue = null;
    // Have a defined private constant for a default value
    // assuming a default value would make more sense than null
    enumValue = DEFAULT_BEST_ENUM_EVER;
}

但你也可以以独特的方式处理每个异常。

Enum BestEnumEver {OPTION_A, OPTION_B, OPTION_C}

// ... elsewhere in your code ...
// How confident are you that stringVar will have an acceptable value?
// How confident are you that the existing enum options will not need to change?
BestEnumEver enumValue;
try {
    // Consider using trim to eliminate extraneous whitespace
    enumValue = BestEnumEver.valueOf(stringVar.trim());
} catch (IllegalArgumentException e1) {
    // handle the situation here ...
} catch (NullPointerException e2) {
    // handle the situation here ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接