Summary
Here is some Java code which uses the BCEL to convert a class file into java byte code.
Advertisement
I have been playing with Java byte code lately and I've just discovered the awesome Byte Code Engineering Library (BCEL). I feel like a kitten with a ball of yarn. Here is the source for a simple decompiler:
import java.io.*;
import java.util.Iterator;
import org.apache.bcel.*;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
import org.apache.bcel.Repository;
public class Decompiler
{
public static void main(String[] argv)
{
try
{
// Load the class from CLASSPATH.
JavaClass clazz = Repository.lookupClass(argv[0]);
Method[] methods = clazz.getMethods();
ConstantPoolGen cp = new ConstantPoolGen(clazz.getConstantPool());
InstructionFactory f = new InstructionFactory(cp);
for(int i=0; i < methods.length; i++)
{
Method m = methods[i];
MethodGen mg = new MethodGen(m, clazz.getClassName(), cp);
decompileMethod(mg, f);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static final void decompileMethod(MethodGen mg, InstructionFactory f)
{
InstructionList il = mg.getInstructionList();
int count = 0;
System.out.println("Method " + mg.getName());
InstructionHandle ih = il.getStart();
while (ih != null) {
System.out.println(ih.toString());
ih = ih.getNext();
}
il.dispose(); // Reuse instruction handles
}
}
I am planning next on a writing a ClassLoader which hacks code as it loads it. This is so much fun!