JDasm: Java Disassembler
Last Modification: 09 February 2011

Introduction to JDasm

Before you learn how to use JDasm you should known the structure of the Java class file. Since we only give you a brief of how it all works, you can always consult The Java Virtual Machine Specification for a deeper knowledge.

JDasm use one main class called DClass to represent the whole structure of a Java class. Through its constructors you can create a new class from scratch:
DClass d = new DClass( "HelloWorld" );
or load an existing class from a file:
DClass d = new DClass( MyAlreadyCompiledClass.class );
The class DClass let you modify almost anything about the top level of the Java class file structure; for instance, we may want to change the super class name and the qualifier for d:
d.setAccessFlags((short)(DClass.ACC_PUBLIC | DClass.ACC_SUPER | DClass.ACC_FINAL) );
Note that by default, the constructor set the superclass to Object and the access flags to public | super.

Besides DClass, another three classes are basic in JDasm: JDasm let you use any single piece of the class file structure as self-standing one; this means for example that you can create one method (through DMethod) and attach it to any of your DClass object. There are several ways of creating a method (or a field): the canonical form to create "public void sayHallo(int times)" is:
DMethod m = new DMethod( DMethod.ACC_PUBLIC, "void", "sayHallo");
m.addArgument("int", "times");
but you can also use a faster way just writing it like a string:
try {
    DMethod m = new DMethod("public void sayHallo(int)");
} catch( CodeParseException e ) {
    System.out.println("Error while parsing the string");
If you want to use the code parsing, then remember to use the fully qualified name for object, for instance java.lang.String.

JDasm offer a class for any attribute known by the JVM plus a class named CustomAttribute for a general purpose attribute.
d.addAttribute(new SourceFileAttribute("hello.java"));
CodeAttribute c = new CodeAttribute();
Of course the code attribute let you to manipulate the bytecode buffer of a method, to manage the exceptions of try-blocks, and can compute for you max locals and max stack field. At build time, an inner verifier will inform you if the produced code attribute is legal to the JVM.

When you are done with modification, you can build the class or build and write it to a file:
d.writeClassToFile( "Hello.class" );

See a complete example on how to build a HelloWorld class