开发者

Convert String to equivalent Enum value

Is it possible for me to convert a String to an equivalent value in an Enumeration, using Java.

I can of course do this with a large if-else statement, but I wou开发者_高级运维ld like to avoid this if possible.

Given this documentation:

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.


Hope you realise, java.util.Enumeration is different from the Java 1.5 Enum types.

You can simply use YourEnum.valueOf("String") to get the equivalent enum type.

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


Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

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


Use static method valueOf(String) defined for each enum.

For example if you have enum MyEnum you can say MyEnum.valueOf("foo")


I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

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.


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. 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. Your class and its setter should protect themselves.

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().

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜