Search code examples
javaguiceinterceptorcglib

Post method invocation interception with Cglib


I was wondering if it is possible to intercept a method after the invocation of the target method? For example as you can see below:

@CleanUp
public void doSomething{
...
}

I want to be able to intercept the method after the method invocation. In above sample, I will do common clean up after the invocation of method.


Solution

  • If you use the standard CGLIB Enhancer you can choose whether you want to execute code before or after the method being proxied is invoked. For instance:

    MyClass proxy = (List<String>)Enhancer.create(MyClass.class, new MyInvocationHandler());
    proxy.aMethodToInvoke();
    .
    .
    .
    class MyInvocationHandler implements MethodInterceptor {
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("Before we invoke the method");
            Object retObj = proxy.invoke(obj, args);
            System.out.println("After we invoke the method");
            return retObj;
        }
    }
    

    So anything after the proxy.invoke call will be code which executes after the method being proxy has been called and has returned.