简体   繁体   English

将字符串转换为等效的枚举值

[英]Convert String to equivalent Enum value

Is it possible for me to convert a String to an equivalent value in an Enumeration , using Java.我是否可以使用 Java 将String转换为Enumeration中的等效值。

I can of course do this with a large if-else statement, but I would like to avoid this if possible.我当然可以用一个大的if-else语句来做到这一点,但如果可能的话,我想避免这种情况。

Given this documentation:鉴于此文档:

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html http://download.oracle.com/javase/1.4.2/docs/api/java/util/Enumeration.html

I am not too hopeful that this is possible without ifs or a case statement.如果没有 ifs 或 case 语句,我不太希望这是可能的。

Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types. 希望您意识到, java.util.Enumeration与Java 1.5 Enum类型不同。

You can simply use YourEnum.valueOf("String") to get the equivalent enum type. 您可以简单地使用YourEnum.valueOf("String")来获取等效的枚举类型。

Thus if your enum is defined as so: 因此,如果您的枚举定义如下:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY
}

You could do this: 你可以这样做:

String day = "SUNDAY";

Day dayEnum = Day.valueOf(day);

假设您使用Java 5枚举(由于您提到旧的Enumeration类,因此不太确定),您可以使用java.lang.Enum子类的valueOf方法:

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

Use static method valueOf(String) defined for each enum . 使用为每个enum定义的静态方法valueOf(String)

For example if you have enum MyEnum you can say MyEnum.valueOf("foo") 例如,如果你有enum MyEnum你可以说MyEnum.valueOf("foo")

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed. 我可能已经过度设计了我自己的解决方案而没有意识到Type.valueOf("enum string")实际存在。

I guess it gives more granular control but I'm not sure it's really necessary. 我想它可以提供更精细的控制,但我不确定它是否真的有必要。

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

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code. 我猜你正在为RuntimeException (或你想抛出的任何异常)交换IllegalArgumentException ,它可能会清理代码。

The other responses about using valueOf(string) are right on, but I would add that you should protect your code for the potential for an invalid string to be passed.关于使用 valueOf(string) 的其他响应是正确的,但我要补充一点,您应该保护您的代码,以免传递无效字符串。 While today your code may only pass strings that correspond with valid enum values it is possible for a future change to the enum or a future change to other parts of your code (or code written by others) to break this assumption.虽然今天您的代码可能只传递与有效枚举值相对应的字符串,但将来对枚举的更改或对代码其他部分(或其他人编写的代码)的更改可能会打破这一假设。

This will be important for cases like when writing a setter for a class's enum member variable.这对于为类的枚举成员变量编写 setter 等情况很重要。 Your class and its setter should protect themselves.您的 class 及其设置器应该保护自己。

The JavaDocs for Enum show that an exception could be thrown on this ( IllegalArgumentException or NullPointerException . You should handle these either generically or specifically. The JavaDocs also show that this function won't like "extraneous whitespace"... so consider using trim(). Enum 的 JavaDocs表明可能会引发异常( IllegalArgumentExceptionNullPointerException 。您应该通用或专门处理这些。JavaDocs 还表明此 function 不喜欢“无关空白”......所以考虑使用 trim( )。

I would probably handle the exceptions generically like this:我可能会像这样一般处理异常:

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

But you could also handle each exceptions in some unique way.但是您也可以以某种独特的方式处理每个异常。

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

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

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