Use Enum to Switch on Strings where one string is a java reserved word.
807589Jan 19 2009 — edited Jan 19 2009Hi,
I'm having problems switching on a string using enums, when one of the strings is a java reserved word. Any suggestions would be appreciated. Or maybe even a suggestion that I should just be stringing together if-else if and doing string compares rather than a switch.
----
I've been using the following method to switch on strings.
public enum MyEnum
{
foo, bar, novalue;
public static MyEnum stringValue(String string)
{
try { return valueOf(string); }
catch (Exception e) { return novalue; }
}
}
Then I can switch like
switch(MyEnum.stringValue( someString )
{
case foo:
break;
case bar:
break;
default:
break;
}
---------------------------
Now I have run into the problem where one of the strings I need to use is "int", which is a reserved word in java, so I have to modify.
What is the best way to handle this?
I could just not add it to the Enum and handle it at the switch like this...
switch(MyEnum.stringValue( someString )
{
case foo:
break;
case bar:
break;
default:
if(someString.equals("int") { ... }
break;
}
OR...
I could change the Enum, and return intx, by checking if the string is "int". I could check before the valueOf, or during the exception, but I know it's not good practice to use Exceptions in the normal execution of your code... as it's not really an exception.
public enum MyEnum
{
foo, bar, intx, novalue;
public static MyEnum stringValue(String string)
{
if(string.equals("int") { return intx; }
try { return valueOf(string); }
catch (Exception e) { return novalue; }
}
}
OR...
public enum MyEnum
{
foo, bar, intx, novalue;
public static MyEnum stringValue(String string)
{
try { return valueOf(string); }
catch (Exception e) {
if(string.equals("int") { return intx; }
else return novalue;
}
}
}