3 Replies Latest reply on Feb 15, 2010 11:53 PM by megalodon

    what happened to $r?

      Shouldn't that work?

      class Foo {
       Object foo() {
       return new Object();
       }
      }
      
      public class Main {
       public static void main(String[] args) throws NotFoundException, CannotCompileException {
       ClassPool cp = ClassPool.getDefault();
       CtClass foocls = cp.get("jatest.Foo");
       CtMethod m = foocls.getMethod("foo", "()Ljava/lang/Object;");
       m.insertBefore("$r x = new Object();");
       }
      }


      I get: compile error: no such class: $r


        • 1. Re: what happened to $r?

          Just for the record, I'd like to take a whack at this one.

           

          Someone can correct me if I am wrong (which might be rare looking at the activity in this forum) but there are 2 errors in my opinion:

           

          1.) You are using a local variable 'x' without adding the local variable first using addlocalvariable() function.

          2.) $r is not available to code added using insertBefore() function. Switching insertBefore() call to insertAfter() call should resolve this bug.

          • 2. Re: what happened to $r?

            repost deleted

            • 3. Re: what happened to $r?
              correction: it turns out that one can declare local variables directly via calls to insertBefore/insertAfter although it should be available only within that code block