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...");
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With