Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe use of Enum valueOf for String comparison on a switch

Tags:

java

enums

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...");
}
like image 797
Xaren Avatar asked Sep 28 '17 15:09

Xaren


2 Answers

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:

like image 169
Peter Lawrey Avatar answered Nov 14 '22 23:11

Peter Lawrey


Using exceptions for flow control is considered as a bad practice.

    String valueToCompare = value.toUpperCase();

    ACTION action = Arrays.stream(ACTION.values())
       .filter(a -> a.name().equals(valueToCompare)).findFirst().orElse(ACTION.NOTVALID);
like image 44
aka Avatar answered Nov 15 '22 00:11

aka