I love code that has a bit of a wow factor. I was known as a “cowboy” at my last job because of it. The fact is, code that “just works” is generally much easier to use than code that you have to figure out what it’s doing underneath. I’ve covered faking dynamic code before, but what about really generating code at runtime? A lot of people do a quick Google and come up with BCEL, just like I originally did (a few years ago that is). However I’ve found Object Web’s ASM API to be much much easier to work with (not to mention much faster and light weight). It is divided into several modules depending how much support you want from the API. At it’s bare minimum it provides all you need to dynamically generate basic class byte-codes at runtime (potentially directly into a ClassLoader, no file needed).
Another way (much easier) to engineer byte-codes at runtime is to use BeanShell. For those who don’t know BeanShell, it’s a lovely little scripting lanuage for Java that can interprate Java source-code with no modifications (to BeanShell or the source code). It can also be dynamically typed, treat getters and setters (Beans methods) as variables, and a whole host of other scripting lovelies. BeanShell uses ASM to expose any class coded in BeanShell to the host application via Class.forName or ClassLoader.loadClass. Thats right, it actually turns it into a Java class. This is not as fast as engineering the entire byte-code yourself, but it’s a lot easier.