Search code examples
javabytecodebcel

BCEL update exceptions table


I want to change a method using BCEL. But I do not know how to update the Exception table. Here's simplified code:

ConstantPoolGen poolGen = classGen.getConstantPool();
InstructionList iList = new InstructionList(method.getCode().getCode());
MethodGen newMethodGen = new MethodGen(method, classGen.getClassName(), poolGen);
for (InstructionHandle handle : iList.getInstructionHandles().clone()) {
    if (I_WANT_TO_WRAP_IT(handle)) {
         iList.insert(handle, MAKE_WRAPPER(handle));
         iList.delete(handle);
    }
}
classGen.removeMethod(method);
newMethodGen.setMaxStack();
newMethodGen.setMaxLocals();
classGen.addMethod(newMethodGen.getMethod());

After this bytecode is properly modified but exception table is unchanged with leads to ClassFormatError because exception table points to nonexisting PC. Any idea how to deal with this?


Solution

  • Normally you don’t need to deal with this as BCEL should take care of it. It seems to me that your mistake is to use a different instruction list than MethodGen. So you’re modifying the underlying code but the offsets are not processed correctly.

    Try to use

    MethodGen newMethodGen = new MethodGen(method, classGen.getClassName(), poolGen);
    InstructionList iList = newMethodGen.getInstructionList();
    

    to ensure that the same list is used by your code and MethodGen.