Typesafe Enum decoding

Ive implemented the typesafe enum pattern, for use in communication packet headers (three implementations, packet Type, packet Opcode, and ErrorCode).

The instances classes of these need to be convertable to and from an int value. I achieved this with a "toInt()" function returning the value associated with the instance, and a static parse(int i) function that uses a switch to return the instance associated with the incoming integer value.

However, the switch statement inside the parse() function is getting large, and ugly looking, not to mention becoming a maintanance nightmare.

I'm contemplating adding a static Hashtable to each typesafe enum class, that holds a list of the instances, with the int code as the key. Is this sound? Is there a "proper" way of doing this, or simply a better way?

PyrosX

[843 byte] By [PyrosXa] at [2007-9-29 1:28:33]
# 1
my typing good is! Sorry... this line:"The instances classes of these need to be convertable to and from an int value."should read:"Instances of each class need to be convertable to and from an int value"
PyrosXa at 2007-7-13 3:50:40 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

Hashtable is overkill.

Each enum element has an ordinal number between zero and (numelements-1). And your enum class contains an array of all its members. Your parse function then looks like:

public MyEnumType parse(final int ordinal) {

return ENUM_ELEMENTS[ordinal];

}

If you want more information on this check out Item 21 of Joshua Bloch's excellent Effective Java - Programming Language Guide.

manowavea at 2007-7-13 3:50:40 > top of Java-index,Other Topics,Patterns & OO Design...