Tue
2
Aug '05
Weave in an aspect via Proxy
by Frank Spychalski filed under articles, Java, Work

If you find this useful, you might like my other articles, too.

This article shows how to use AOP with nothing but java – No code generation or bytecode manipulation.

Sample Scenario:
You want to insert logging statements for every call to every method of a certain class. This sounds like the default example used to promote AOP, but there is an easier solution if you know about java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler.

Let’s take a random interface like

public interface MyInterface {
  public void methodA(int i, String s, String t) throws IOException ;
}

Use a factory to get the Implementation or the proxy and anything you like to switch between using a proxy and not using it.

public class MyInterfaceFactory {
  public static MyInterface getMyInterface()  {
    Object impl = new MyInterfaceImpl();
    String proxySwitch = System.getProperty("myinterface.logging");

    if (proxySwitch == null) {
      return (MyInterface) impl;
    }
    InvocationHandler proxy = new LoggingProxy(impl);
    MyInterface bf2 = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(),
                  new Class[] { MyInterface.class }, proxy);
    return bf2;
  }
}

An implement InvocationHandler to create a LoggingProxy. To keep this example simple, I used System.out.println, use any flavor of logging you like in the real world.

public class LoggingProxy implements InvocationHandler {
  private Object target;
  public LoggingProxy(Object t) {
    target = t;
  }

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("Method " + method.getName());
    for (int i = 0, l = args.length; i < l; i++) {
      System.out.println("Object[" + i + "] " + args[i].getClass().getName() + " " + args[i]);
    }

      return method.invoke(target, args);
  }
}

This implementation looks like it will work, but it has the slight problem, that it might change the behaviour of your application :-(

Pages: 1 2


One Response to “Weave in an aspect via Proxy”

  1. 1

    [...] My article about Proxy and InvocationHandle made me think about other useful classes. I don’t know how long it took me to realize how much useful stuff can be found in Collections. [...]

    amazing development (August 8th, 2005 at 15:56)

Any comments? Or questions? Just leave a Reply: