Friday, July 01, 2005

Enum Code Generation

Once you start playing with code generation, you can't stop. At least, I can't.

One of the new features in J2SE 5.0 (or 1.5) is enums. I've missed enums for a long time, and I usually used the unsafe "static int" enums when I had to use them. The new version of Java provides real, type-safe, enums - but unfortunately, I can't use it, because I code for an old version of the language.
So I developed my own type-safe enums, based on Joshua Bloch's suggestion from the Effective Java book.

My idea is to describe the enum using XML, and then use XSLT to translate it to Java. The XSLT stylesheet adds all the boilerplate code required by type-safe enums.

One advantage of using XML+XSLT is portability between languages: at work, I build a Java component of a mostly-C++ project. The other engineers in my group have defined their enums in C++, and currently, to communicate with their code, I have to manually update my enum with theirs. If the enum is defined by using XML, we can write another XSLT that translates it to "regular" C++ enums.

I will publish my XML format + XSLT translator here, after I clean it a bit.


No comments: