示例#1
0
  public void testInsertLocal() throws Exception {
    CtClass cc = sloader.get("test2.InsertLocal");
    CtMethod m1 = cc.getDeclaredMethod("foo");
    m1.insertBefore("{ i = s.length(); d = 0.14; }");
    m1.insertAfter("{ field = i; }");

    CtMethod m2 = cc.getDeclaredMethod("run2");
    m2.insertAt(22, "{ s = \"12\"; k = 5; }");

    CtMethod m3 = cc.getDeclaredMethod("run3");
    m3.instrument(
        new ExprEditor() {
          public void edit(NewExpr n) throws CannotCompileException {
            n.replace("{ i++; $_ = $proceed($$); }");
          }

          public void edit(FieldAccess f) throws CannotCompileException {
            f.replace("{ i++; $_ = $proceed($$); }");
          }

          public void edit(MethodCall m) throws CannotCompileException {
            m.replace("{ i++; $_ = $proceed($$); }");
          }
        });

    cc.writeFile();
    Object obj = make(cc.getName());
    assertEquals(317, invoke(obj, "run"));
    assertEquals(7, invoke(obj, "run2"));
    assertEquals(3, invoke(obj, "run3"));
  }
示例#2
0
  public void testInsertAt() throws Exception {
    CtClass cc = sloader.get("test2.InsertAt");
    CtMethod m1 = cc.getDeclaredMethod("foo");
    int line = 6;
    int ln = m1.insertAt(line, false, null);
    int ln2 = m1.insertAt(line, "counter++;");
    assertEquals(ln, ln2);
    assertEquals(7, ln2);

    line = 8;
    ln = m1.insertAt(line, false, null);
    ln2 = m1.insertAt(line, "counter++;");
    assertEquals(ln, ln2);
    assertEquals(8, ln2);

    CtMethod m2 = cc.getDeclaredMethod("bar2");
    int ln3 = m2.insertAt(20, "{ int m = 13; j += m; }");
    assertEquals(20, ln3);

    cc.writeFile();
    Object obj = make(cc.getName());
    assertEquals(7, invoke(obj, "foo"));
    assertEquals(25, invoke(obj, "bar"));
  }