This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Doesn't seem that messy to me. You talk about "wrapping the enum in a class" but that seems unnecessary - you can define the static field and method as part of the enum itself.
There is something similar to this already built into enums - the ability to look up values by name, using a String. E.g.
This build-in functionality is very similar to what you want, but it only works using the identifiers for the enum values you have defined - in Type above, that's "ABC", "DEF", "GHI". If you want this sort of easy lookup you can often choose your identifiers to match the existing strings you want to use for lookup. Except for things like "*&", "��", "^^" you can't do this, because those aren't legal Java identifiers. So, you've got to use a Map as a static field, just as you've done above.
Expanding on what Jim said: since just one instance of the Enum will be constructed for each value, you could add the values into the map in the constructor, eliminating the separate static block; i.e.,
It is a compile-time error to reference a static field of an enum type that is not a compile-time constant (�15.28) from constructors, instance initializer blocks, or instance variable initializer expressions of that type. It is a compile-time error for the constructors, instance initializer blocks, or instance variable initializer expressions of an enum constant e to refer to itself or to an enum constant of the same type that is declared to the right of e.
(See also the discussion section which follows.) You can't reference a static field (the Map, in this case) from an enum constructor, since it hasn't been initialized yet. I suppose they could have allowed this to work if the static field were allowed to be declared before the enum values, but that would've muddied up the enum definition, and still been error prone, I think. Unless the compiler were to force the correct ordering of the declarations. They didn't do that though, so the short answer is, we can't reference a static field in an enum constructor - that's why I used the static block. [ April 03, 2006: Message edited by: Jim Yingst ]