Sunday, 29 May 2016

Understanding CGLIB

CGLIB is a byte code generation library which creates and link proxy classes at runtime.As java classes can be dynamically linked , we can add new classes in running java program.It simply creates a subclass of your class by reading its byte code. Under the hood it uses ASM which is a byte code manipulation framework. ASM helps CGLIB to generate java byte code at runtime.

Frameworks like spring, hibernate, mockito uses CGLIB. Spring AOP uses proxy-based Aspect Oriented Programming which has a feature of method interception.Hibernate implemented a feature of returning proxy of an object of entity graph from database where child entities are fetched from database when required.Hibernate uses CGLIB for this feature.

Lets start with some coding examples. CGLIB has a class named Enhancer which helps us to create proxy class for all the classes implementing or not implementing any interface. It is quite similar to Proxy class in java.