Trying it out

After setting the CLASSPATH try to use the listclass utility:

	% java listclass -code -constants java.lang.StringBuffer | more

Then take a look at the source code of listclass.java. You may also want to try patchclass.java which patches string constants in class files. For example:

	% java listclass -constants patchclass.class

	% java patchclass string foobar patchclass.class

	% java listclass -constants _patchclass.class

You'll note the subtle difference...

Java class objects can be traversed with the Visitor design pattern as described in the notorius "Design Patterns" book. The JasminVisitor class, e.g., makes use of it in order to convert class files into the Jasmin assembler format. Try

	% java JasminVisitor listclass
	% more listclass.j

Dynmically creating classes using a class loader

Take a look at ProxyCreator.java which dynamically creates byte code for an ActionListener proxy, loads and uses it:

	% java de.fub.bytecode.util.JavaWrapper ProxyCreator

Simple profiling example

There is an example program named helloify.java included in the distribution that takes class files and modifies all of their methods, so that they will print "Hello" and their name and signature before doing anything else. This could be useful, e.g., to do some kind of profiling. Modifying the program with itself gives funny results:

	% java helloify helloify.class

This yields a class file named helloify_hello.class, which we can use to modify itself again:

	% java helloify_hello helloify_hello.class
	Hello from public static void main(String[])
	Hello from private static final void helloifyClassName(de.fub.bytecode.classfile.JavaClass)
	Hello from private static final de.fub.bytecode.classfile.Method helloifyMethod(de.fub.bytecode.classfile.Method)
	...
yields helloify_hello_hello.class and so on. Every time the printed message will be repeated once more.
Transformations like this can also be applied by a ClassLoader at load-time, for example to insert code that logs method calls or class instantiations. This is user-transparent since the original code remains unaltered.

Mini language

Take a look at the Mini language I wrote for demonstration purposes:

Other examples

Other code examples of the API are HelloWorldBuilder.java which creates a simple "HelloWorld" class and Peephole.java which remove NOPs (No operation instructions) from all methods of a class.

The Class2HTML tool converts class files into HTML files. Here you can find example output generated with this tool.