Javassist:在catch块的开头插入一个方法
Javassist: insert a method at the beginning of catch block
我有代码:
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\")");
}
}
});
您应该尝试获取您要查找的块的源代码中的行号。
试试这样的东西:
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\")")
}
}
我有代码:
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\")");
}
}
});
您应该尝试获取您要查找的块的源代码中的行号。
试试这样的东西:
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\")")
}
}