Jazzpect

jazzpect provides an implementation of aopalliance 1.0 API.

Jazzpect Example

Following Jazzpect example demonstrates how to measure execution time of methods in target class samples.jazzpect.Foo. In the example, MethodInterceptor is an interface specified by AOP alliance.

Initializer will setup class instrumentation so, that when then actual class (samples.jazzpect.Foo) is loaded into VM, its methods are augmented so, that calls to foo1() and foo2() are replaced with calls to MethodInterceptor.invoke(MethodInvocation), which is implemented by Sample1 class. This method then calls MethodInvocation.proceed() which calls the actual foo1() and foo2().

Note, how arguments can be altered while in MethodInterceptor.invoke() method. Care must be taken, that if modifying arguments, it does not change the type of argument.

Given a class samples.Foo as

package samples;

public class Foo {
   public static void main(String[] args) {
      foo1("a string");
      System.out.println("> " + foo2(3));
   }

   public static void foo1(String s) {
      System.out.println("> " + s);
   }

   public static int foo2(int i) {
      return i+1;
   }
}

And samples.jazzpect.Sample1 as

package samples.jazzpect;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import net.sf.jiapi.jazzpect.Initializer;

public class Sample1 implements MethodInterceptor {
   public static void main(String args[]) throws Exception {
      Initializer i = new Initializer(new String[] { "samples.*" }, null,
            "samples.*", new Sample1());
      
      i.runMainMethod("samples.jazzpect.Foo", null); // Run the main method of class
   }

   // Interface MethodInterceptor: ---------------------------
   public Object invoke(MethodInvocation mi) throws Throwable {
      Object[] arguments = mi.getArguments();

      if (arguments[0] instanceof String) {
         arguments[0] = "MODIFIED BY JIAPI: " + arguments[0];
      }

      long l1 = System.currentTimeMillis(); // ###
      Object o = mi.proceed();              // ###  Make the actual call to underlying method
      long l2 = System.currentTimeMillis(); // ###

      System.out.println("### It took " + (l2 - l1) + " ms to invoke "
            + mi.getMethod().getName());

      return o;
   }
}

Running Sample1 will result in following output. No other configuration is needed other than adding jiapi jar files into classpath.

> MODIFIED BY JIAPI: a string
### It took 0 ms to invoke foo1
### It took 0 ms to invoke foo2
> 4