Safe use of Enum valueOf for String comparison on a switch

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:


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

Tags:

Java

Enums