1 Reply Latest reply on Feb 18, 2010 8:09 AM by megalodon

    determining if code passed to insertAfter() is executed after an exception handler or before normal return

      Hello,

       

      Quick question. As far as my understanding goes, the source code provided to the CtMethod.insertAfter() is inserted 'at the end of the method' i.e., before every 'return' statement and after every exception handler in it (not as a 'finally' block). Supposing that we call the code-block passed to the insertAfter() method as block A.

       

      My question is this: Is there anyway to distinguish, from block A, whether block A is getting executed upon normal return of the method or if it was executed after an exception handler got done?

       

      This will help me determine if the method ran successfully or if an exception was handled. Thanks

        • 1. Re: determining if code passed to insertAfter() is executed after an exception handler or before normal return

          I didnt know much about CtMethod.instrument() and ExprEditor and its edit methods before. You can use them to solve the above problem:

          // Suppose you want to know from where the insertBefore code of 'myCtMethod' is running, You can add a boolean 
          // field to the class for this purpose. unfortunately, we need a FIELD for every 'instrumented' method because Javassist DOES NOT ALLOW access to LOCAL VARIABLES 
          // including those added using its own addLocalVariable() method. In our case, I call 
          // the boolean field as 'inHandler'. Set it to false upon initialization.
            
             myCtMethod.instrument(new ExprEditor() {
             public void edit(Handler myHandler) throws CannotCompileException {
              try {
             
               // insertBefore inserts the statement before the catch block is entered. You can even change the exception here, i think.
               // Here I set inHandler to true signifying entry into the catch block.
               myHandler.insertBefore("inHandler = true;");  // inHandler is an (added) field of the CtClass containing myCtMethod
               
               // Below statement prints some description of the handler object, if needed.
               myHandler.insertBefore("System.out.println(\"Instrumentation detected presence of a Handler for " + myHandler.getType().getName() + " at line number " + myHandler.getLineNumber()+"\");");
              } catch (NotFoundException ntfnde) {
               ntfnde.printStackTrace();
              }
             }
            });
          
          
          // The below if statement will distinguish between normal code and exception handler code and execute accordingly
            sayCtM.insertAfter("if (inHandler == true) System.out.println(\"Running within a handler.\"); else System.out.println(\"Running in normal code\");");
          

           

          Message was edited by: Arvind K