Thursday, April 1, 2010

CGLIB introduction

Today I would like to briefly discuss the bytecode generation framework, CGLIB.

There are a lot of these frameworks, each one works at the different level of abstraction.
Recently I was looking for a high-level framework that would let me to dynamically change my classes providing its proxy and substituting the functionality of some methods.

While the most obvious jdk proxies can do the job (java.lang.reflect.Proxy), I've figured out, that when I don't have both an interface and implementation of my to-be-proxified class, it just doesn't work. So I've found another solution, a library called CGLIB

The only significant drawback for me was a lack of comprehensive documentation, in fact I've found only one decent tutorial here (It could be great if someone could point me on more tutorials about this tool).
Anyway, I think that a beginner's level introduction can't harm so I fill the gap and share the experience :)

So CGLIB is a bytecode generation library, that relies on low-level
ASM framework.
So in order to create a working example we'll need to open a regular java project and add two jars as a dependency (the latest versions available at the moment):

- cglib-2.2.jar
- asm-all-3.2.jar

We will 'proxify' the mock Algorithm class which is supposed to implement some long-running algorithm. We would like to measure its execution time.

So we create our algorithm like this:



Now the most interesting part of the program:
We'll create a class that adds the 'measurements'. This class will be used by CGLIB to proxify our algorithm, so it should implement net.sf.cglib.proxy.MethodInterceptor

The class looks like this:



The last class is the main class. Here we will actually create the proxy so here we'll see some CGLIB related code:



The output of this program is predictable :)

Before
running the algorithm
After
Took: 500 ms

Thats all, thanks for your attention
Mark Bramnik

12 comments:

  1. I am an ardent Java fan. Your 'proxifying' is definitely a very interesting read. Good job Mark!

    ReplyDelete
  2. Thanks a lot, I'll try to update this blog with different java-related posts!

    ReplyDelete
  3. Thanks for the post. I was looking for some documentation on CGLib.

    ReplyDelete
  4. First neat documentation of CGI LIB that I could come across.

    ReplyDelete
  5. very simple nice introduction. thumbs up

    ReplyDelete
  6. Simple and Perfect! CGLIB is extensively used by a lot of technologies - EJB, Spring AOP, AspectJ etc.

    ReplyDelete
  7. Very simple and nice introduction on CGLIB for beginners..

    - Karthik Elayaperumal

    ReplyDelete
  8. This answered all my questions. Thanks.

    ReplyDelete
  9. For further reading: You might be interested in this summary that I wrote: http://mydailyjava.blogspot.no/2013/11/cglib-missing-manual.html

    ReplyDelete