Ankur
Ankur

Reputation: 51100

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

Upvotes: 129

Views: 199914

Answers (5)

MustardMan
MustardMan

Reputation: 101

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

Upvotes: 1

fIwJlxSzApHEZIl
fIwJlxSzApHEZIl

Reputation: 13270

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.

Upvotes: 6

AlexR
AlexR

Reputation: 115328

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

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

Upvotes: 9

adarshr
adarshr

Reputation: 62573

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

Upvotes: 273

Xion
Xion

Reputation: 22770

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

Upvotes: 20

Related Questions