Search code examples
javaspringcglib

Java CGlib Enhancer for Selective class or method


I would like to develop an utiity class to intercept few methods of my project. Currently my project has 120+ java files and I would like to intercept say 15 methods in 10 files. How to achieve that using Cglib enhancer?

Also lets say I have following code

class A{
 B b = new B();
 C c = new C():
 void m1(){
   b.m2();
   c.m3();
 }
}

I would like to intercept only method m1() and m3(). Is it possible, if yes how to do that?


Solution

  • Cglib works by creating subclasses for your types at runtime. Therefore, what you suggest is not possible using cglib. For your class A, cglib's Enhancer creates a class similar to:

    class A$Proxy extends A {
    
      MethodInterceptor interceptor;
    
      @Override
      void m1(){
        interceptor.intercept("m1");  
      }
    }
    

    This way, cglib can call your code instead of the original implementation. However, the field instances of the A class are not virtual and cannot be modified by cglib due to the subclassing approach. With cglib, no existing code is actually changed.

    Instead, you should look into using Java agents which allow you to redefine existing code what allows for the AOP programming style that you are looking for. There are libraries more powerful than cglib like for example Byte Buddy, a library that I wrote. I once wrote down an example for such AOP with Byte Buddy on the example of logging if you are interested: http://mydailyjava.blogspot.no/2015/01/make-agents-not-frameworks.html