users@jaxb.java.net

Re: Enum Plugin ?

From: Kenny MacLeod <kennym_at_kizoom.com>
Date: Sun, 31 Dec 2006 00:01:45 +0000

I may be missing something obvious here, but what's wrong with this:

values()[ordinal];

I think the reason there's no static method for this on enums already is
that it's that simple.


Hanson Char wrote:
> Just realized in most cases it's probably better/simpler to implement
> the fromOrdinal method like this:
> ...
> public static USState fromOrdinal(int ordinal) {
> for (USState c: USState.values()) {
> if (c.ordinal() == ordinal)
> return c;
> }
> throw new IllegalArgumentException(String.valueOf(ordinal));
> }
> ..
> Hanson
>
> On 12/30/06, *Hanson Char* <hanson.char_at_gmail.com
> <mailto:hanson.char_at_gmail.com>> wrote:
>
> Hi,
>
> Recently I needed to construct an xjc plugin that adds a
> fromOrdinal() method for every enum classes generated. An example
> is given below.
>
> However, I couldn't find an easy way to generate the static block,
> besides resorting to use the JDefinedClass.direct() method. One
> undesirable side effect is that it seems such "direct" static block
> is always generated at the end of the source file, rather then
> observing the execution order of the plugin.
>
> Is there a better way ?
>
> Also, if anyone finds this plugin interesting, I can host it at
> jaxb2-commons as a separate plugin project.
>
> Regards,
> Hanson
>
> public enum USState {
> ...
> // Generated by the enum-plugin
> private final static HashMap<Integer, USState> ordinalToEnum =
> new HashMap<Integer, USState>();
>
> // Generated by the enum-plugin
> public static USState fromOrdinal(int ordinal) {
> return USState.ordinalToEnum.get(ordinal);
> }
>
> // Generated by the enum-plugin
> static {
> for (USState t : USState.values())
> ordinalToEnum.put(t.ordinal(), t);
> }
> }
>
>