You can use Dynamic Proxy to wrap a method call, here is an example:
First you need to create the InvocationHandler class:
public class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("About to invoke " + method + "\n with argument " + args); Object rv = method.invoke(target, args); System.out.println(" Call returned " + rv);
Then create a factory to get the object and wrap it with the previous proxy created.
public class MyFactory { public static MyInterface getMyInterface() { MyInterface mc = new MyClass(); InvocationHandler h = new MyInvocationHandler(mc); MyInterface mi = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(), new Class[] { MyInterface.class }, h); return mi; } }
Hope that helps you.
source share