Saturday, 23 May 2009

Implementing Aspect Oriented Programming by Hacking Java Class Files Programmatically

This is an Apache-licensed Java library for manipulation of .class files which can be useful when hacking together aspect-oriented extensions to Java. The Apache license allows you to use BCEL for commerical projects. The heart of BCEL is the JavaClass class, which represents a Java class in memory. A ConstantPool class represents the constant pool. BCEL supports something called load-time reflection, whereby these classes all become useful. I'll keep coming back to this point, because it is something that goes beyond the scope of the Reflection API. It can be used to fundamentally change the behaviour of Java classes.
  • BCEL supports load-time reflection. Run-time reflection is built into Java via the Reflection API, load-time reflection allows you to modify the bytecode instruction set at the time of loading the class. How does this differ from a custom classloader? Well, you still need to write a custom class loader, which instead of passing bytecode directly to JVM, first passes it through your run-time system using BCEL API.
  • It has a Static API to map structures described in the JVM specification. It also has a Generic API to create and transform class files dynamically, its heart is the ClassGen class, which allows you to create new class files, and add methods and attributes dynamically.
  • Comes with a bytecode verifier called JustIce.
  • Comes with a Class2HTML utility to generate html bytecode documentation for classfiles. This is interesting to see e.g. how synchronized code is implemented at the bytecode level.

So, if you want to write some bytecode manipulation programs, don't do it from scratch, but use BCEL as a basis!

No comments: