Javassist:在catch块的开头插入一个方法 [英] Javassist: insert a method at the beginning of catch block
本文介绍了Javassist:在catch块的开头插入一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有代码:
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\")")
}
}
此代码段将print语句插入方法的开头,这不是我想要的。我希望将代码放置为:
This code snippet inserts the print statement at beginning of the method, which is not what I want. I want the code to be placed like:
void foo() {
try {
a();
} catch(Exception e) {
System.out.println("catch block");//inserted by javassist
b();
}
}
你知道我的代码哪里写错了吗?
Any idea where my code got wrong?
一种更优雅的处理方式
CtBehavior.instrument(new ExprEditor() {
@Override
public void edit(Handler h) throws CannotCompileException {
if( !h.isFinally()) {
h.insertBefore("System.out.println(\"catch block\")");
}
}
});
参考: http://www.javassist.org/tutorial/tutorial2.html#intro
推荐答案
您应该尝试在要查找的块的源代码中获取行号。
You should try to get the line number in the source code of the block you are looking for.
尝试
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\")")
}
}
这篇关于Javassist:在catch块的开头插入一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文