import org.apache.bcel.*;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.*;
public class HelloWorldBCEL {
public static void main(String[] args) throws Exception {
JavaClass helloWorldClass = Repository.lookupClass("HelloWorld");
ClassGen classGen = new ClassGen(helloWorldClass);
ConstantPoolGen constantPoolGen = classGen.getConstantPool();
Method[] methods = helloWorldClass.getMethods();
for (Method method : methods) {
if (method.getName().equals("sayHello")) {
MethodGen methodGen = new MethodGen(method, helloWorldClass.getClassName(), constantPoolGen);
InstructionList instructionList = methodGen.getInstructionList();
InstructionFactory instructionFactory = new InstructionFactory(classGen, constantPoolGen);
instructionList.insert(instructionFactory.createFieldAccess("java.lang.System", "out", new ObjectType("java.io.PrintStream"), Constants.GETSTATIC));
instructionList.insert(new PUSH(constantPoolGen, "Hello, BCEL!"));
instructionList.insert(instructionFactory.createInvoke("java.io.PrintStream", "println", Type.VOID, new Type[] { Type.STRING }, Constants.INVOKEVIRTUAL));
methodGen.setMaxStack();
methodGen.setMaxLocals();
methodGen.update();
}
}
classGen.getJavaClass().dump("HelloWorld.class");
}
}