Re: switch using strings
On Sun, 20 Feb 2011 21:24:37 +0000, Dirk Bruere at NeoPax
<dirk.bruere@gmail.com> wrote, quoted or indirectly quoted someone who
said :
...which obviously won't work.
I have a series of packets coming in with a header that contains a
message name in text. I need to find a neat way to do a kind of switch
statement on the message name. Any ideas?
I have often wished Java would implement strings on case statements. I
had it in my DOS-based language, Abundance.
The idiom I used most often now is to create an enum.
Then I convert the string to an enum with valueOf or valueOfAlias (a
method I write like alias that also accepts case-insensitive alias for
each enum).
Then you can use the enum in a switch.
The logical way to write valueOfAlias is as a HashMap. I could not
figure out how to allocate a common static HashMap, so I did it by
scanning each of the constants. See
http://mindprod.com/jgloss/enum.html
for sample code. See the workaround suggested by Piotr Kobzda. You
have to put the HashMap in a separate little class to do it properly.
Enums have some quirks because they are just a form of inner class.
Inner classes can't have statics. This has always struck me as an
arbitary restriction, and it comes to bite here.
Enum.valueOf is implemented like this:
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum const " + enumType +"." + name);
}
enumConstantDirectory appears to be some sort of static Map, but there
is no other mention of it. It seems to just appear out of nothing,
presumably constructed by special magic when the compiler parses an
enum.
--
Roedy Green Canadian Mind Products
http://mindprod.com
Refactor early. If you procrastinate, you will have
even more code to adjust based on the faulty design.
..