I'm getting myself a bit tied up with enums. I have an enum with an int value and a String description which uses symbols:
However, what I want to do is find a clean way to return the value for a given descriptor. I can do it by wrapping the enum in a class with :
but now my nice clean type got all messy. Is there a cleaner approach?
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.
The "uncleanliness" that you are observing is called the object-oriented programming paradigm, which seems to have become linked with the notion of static type inheritance.
Simply, don't try to pile as many methods into a type as you can. Abstract atomic and unrelated behaviour.
(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.
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.
[ April 03, 2006: Message edited by: Jim Yingst ]