users@jaxb.java.net

Enum Plugin ?

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

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