Javassist: insert a method at the beginning of catch block

隐身守侯 提交于 2020-02-06 02:51:08

问题


I have code:

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\")")
   }    
}

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?


A more elegant way to handle it

 CtBehavior.instrument(new ExprEditor() {
            @Override
            public void edit(Handler h) throws CannotCompileException {
                if( !h.isFinally()) {
                    h.insertBefore("System.out.println(\"catch block\")");
                }
            }
        });

Ref: http://www.javassist.org/tutorial/tutorial2.html#intro


回答1:


You should try to get the line number in the source code of the block you are looking for.

Try with something like this:

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\")")
   }    
}


来源:https://stackoverflow.com/questions/51738034/javassist-insert-a-method-at-the-beginning-of-catch-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!