This content has been marked as final.
Show 1 reply
-
1. Re: determining if code passed to insertAfter() is executed after an exception handler or before normal return
megalodon Feb 18, 2010 8:09 AM (in response to megalodon)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