Safe use of Enum valueOf for String comparison on a switch

Xaren :

How to safe implement the use of valueOf in case i get a String different than the supported on the enum ACTION. I mean is possible to force to ACTION.valueOf(valueToCompare) to get a valid value even when happens that valueToCompare is not a valid enum member

I get an expected execution when valueToCompare is "CRY" or "CRYALOT" or "cryalot" etc.

And i get java.lang.IllegalArgumentException on cases like in the code.

public enum ACTION{
    CRY,
    CRYALOT;
}

public static void main(String[] args) {

    String valueTocompare = "posible not expected value".toUpperCase();

    switch (ACTION.valueOf(valueToCompare)) {
        case CRY:
            System.out.println("Cry");
            break;
        case CRYALOT:
            System.out.println("Cry a lot");
            break;
        default:
            System.out.println("catch posible not expected value");
            break;
    }
}

EDIT & used SOLUTION:

I solved this by using a try-catch as @Peter Lawrey suggested:

public enum ACTION{
    CRY,
    CRYALOT,
    NOTVALID;
}

public static void main(String[] args) {

    String valueToCompare = "NOTVALID";
    ACTION action;
    try {
        valueToCompare= "variable posible not expected value".toUpperCase();
        action = ACTION.valueOf(valueToCompare);
    } catch(IllegalArgumentException e){
        System.out.println("Handled glitch on the Matrix");
        action = ACTION.NOTVALID;
    }

    switch (action) {
        case CRY:
            System.out.println("Cry");
            break;
        case CRYALOT:
            System.out.println("Cry a lot");
            break;
        default:
            System.out.println("catch posible not expected value");
            break;
    }

    System.out.println("We continue normal execution on main thread...");
}
Peter Lawrey :

You need to catch the IllegalArgumentException

try {
    switch (ACTION.valueOf(valueToCompare)) {

    }
} catch (IllegalArgumentException iae) {
    // unknown
}

Or you can create your own function which does this.

public static <E extends Enum<E>> E valueOf(E defaultValue, String s) {
    try {
        return Enum.valueOf(defaultValue.getDeclaringClass(), s);
    } catch (Exception e) {
        return defaultValue;
    }
}

Note: switch(null) throws a NullPointerException rather than branching to default:

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474267&siteId=1