我有代码:
ControlFlow cf = new ControlFlow(method);
for (ControlFlow.Block block : cf.basicBlocks()) {
ControlFlow.Catcher catchBlocks[] = block.catchers();
for (int i = 0;i < catchBlocks.length;i++) {
int position = catchBlocks[i].block().position();
method.insertAt(position, "System.out.println(\"catch block\")")
}
}
此代码段在方法的开头插入了打印语句,这不是我想要的。我希望将代码放置为:
void foo() {
try {
a();
} catch(Exception e) {
System.out.println("catch block");//inserted by javassist
b();
}
}
知道我的代码哪里出错了吗?
一种更优雅的处理方式
CtBehavior.instrument(new ExprEditor() {
@Override
public void edit(Handler h) throws CannotCompileException {
if( !h.isFinally()) {
h.insertBefore("System.out.println(\"catch block\")");
}
}
});
答案 0 :(得分:1)
您应该尝试在要查找的块的源代码中获取行号。
尝试如下所示:
ControlFlow cf = new ControlFlow(method);
for (ControlFlow.Block block : cf.basicBlocks()) {
ControlFlow.Catcher catchBlocks[] = block.catchers();
for (int i = 0;i < catchBlocks.length;i++) {
int position = catchBlocks[i].block().position();
// Get source code line position
int lineNumber = method.getMethodInfo().getLineNumber(position );
method.insertAt(lineNumber+1 , "System.out.println(\"catch block\")")
}
}