users@jaxb.java.net

Re: Enum Plugin ?

From: Hanson Char <hanson.char_at_gmail.com>
Date: Sat, 30 Dec 2006 01:29:27 -0800

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> 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);
> }
> }