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
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):
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 :)
running the algorithm
Took: 500 ms
Thats all, thanks for your attention