JavaOne '02: TS-2558: A Crash Course in Dynamic Class Generation
Dynamically building a Java class file is useful in a surprising number of
situations. It can be quite a daunting task, especially if you generate
the bytecode directly, as opposed to generating a .java source file and compiling
it.
I gave a crash course at JavaOne '02 providing an introduction to the technologies
you can use to build bytecodes dynamically, along with the sorts of problems
this can solve.
This page holds the resources from that talk: links, example code & the
slides from the presentation.
Bytecode toolkits
When choosing a bytecode toolkit, remember that it is a large investment
in time to learn to use one - so you don't want it to not be powerful enough
for your needs, nor do you want it to have a restrictive license that might
mean you can't use it for everything you might potentially do. Here
are a couple that I recommend:
- gnu.bytecode (by Per
Bothner) is the toolkit I wrote the example using. It's distributed
as part of Kawa.
- Jakarta/Apache
Byte Code Engineering Library (BCEL). I only found this in the
last year or so and haven't had a chance to play with it yet. It looks
to contain more tutorials & documentation than gnu.bytecode, and might
be a better choice for a beginner.
Examples - systems that use dynamic class generation
- Both the Ozone database and
Xalan (Apache XSLT) use BCEL.
- java.lang.reflect.Proxy generates a class on the fly, but without using
a bytecode toolkit (you can see how difficult it is without one if you go
and look!)
- java.lang.reflect.Method invoke() apparently uses dynamic class generation
to speed up the invoke() call if it is used repeatedly in 1.4.
- There are many other example that I'm not going to list here. BCEL
maintains a list of the systems using it on their page, last time I checked.
Slides from the talk
Available in slides.zip
Example code
I spent a lot of time going over a particular example, that of a very simple
RowSet implementation. The example code is available in Rowcache.zip
- Paul McLachlan (pdm@acm.org), April 5,
2002.