2 Replies Latest reply on Sep 14, 2008 12:43 PM by Sanjay Acharya

    try finally around a method

    Sanjay Acharya Newbie

      Hi,

      Is there a way to add try/finally around a method using java assist? I do not want to create a whole new method and delegate to it but simply alter the existing method. I could not find a way of accomplishing the same without having to create a foo$impl() or equivalent and delegating to the same.

      Also, is there a way to obtain the string code in an existing method's body via CtMethod? I mean the actual method body code.

      The following is what I am trying to accomplish:

      public void foo() {
       System.out.println("Foo");
      }
      


      to be changed to:

      public void foo() {
       try {
       System.out.println("Entering foo");
       System.out.println("Foo");
       } finally {
       System.out.println("Exited foo");
       }
      }
      


      Thanks in advance.

        • 1. Re: try finally around a method
          Sanjay Acharya Newbie

          I can accomplish the above by doing an :

          ctMethod.insertAfter("System.out.println(\"After Foo\"", true).
          


          and then an:
          ctMethod.insertBefore("System.out.println(\"Before Foo\"");


          However I cannot seem to access a local variable in the finally for example:
          long start = System.currrentTimeMillis();
          System.out.println("Before Foo");
          try {
           System.out.println("Foo");
          } finally {
           long end = System.currentTimeMillis();
           System.out.println("Foo too:" + (end - start));
          }
          


          The problem is when I am altering the method for the finally, I cannot access the start variable I introduced.

          Any tips would be welcomed.

          • 2. Re: try finally around a method
            Sanjay Acharya Newbie

            I thing I figured it out. I did the following:

            final String beforeMethod = "{long startTime = System.currentTimeMillis(); System.out.println(\"Before Foo\");";
            final String afterMethod = "finally {long diff = System.currentTimeMillis() - startTime; System.out.println(\"Foo completed in:\" + diff);}}";
            
            mold.instrument(
             new ExprEditor() {
             public void edit(MethodCall m)
             throws CannotCompileException
             {
             m.replace(beforeMethod + " try {$_ = $proceed($$); } " + afterMethod);
             }
             });