Monday, February 26, 2007

CGLibbing CGLib

So for my first couple of posts, I figured I would go back and look at some of the many problems I've encountered in my daily life of Java development.

The first problem I came across was trying to CGLib an already CGLibbed object (yea...sounds a little shady to me too).

Anyways, here's the background:
- We use Hibernate (3.1.3 if you want to get specific)
- We wanted the ability to dynamically add getters and setters to objects on the fly (and these getters/setters would actually get/put information from/to another member object)

So, myself and another work colleague set out to see what we could do. First step was to actually figure out how CGLib works. This definately was a little painful since I found the documentation on CGLib to be a little poor (at best!). After a couple hours, we finally got through the basics (read: Enhancer is the class to pay attention to) and were merrily running down our unit testing path.

How far did we actually get? Quite far actually. Dynamic getters/setters? Check. Getters and setters that mapped to other member objects? Check. Being able to save these objects? BOOM!

It seems that Hibernate didn't like what we were doing. What exactly was the problem? The object we were giving Hibernate back was one it couldn't understand. So it threw one of its many exceptions (don't recall the exact one) and we were stuck. But we weren't licked yet! We decided to dive a little deeper...

So how exactly did Hibernate know that the object we were giving it wasn't one it could understand? It appears that Hibernate was calling getClass() and comparing the result against its mapping files. And our CGLibbing process meant that the getClass() wasn't really what we had (I believe it returned the Enhancer class). So further on we trudged!

(Note: The rest of the story is a little hazy at best, so I apologize now)
The short and sweet of the finale is that we investigated modifying the code that did the getClass() calling. I do believe it involved some Hibernate Interceptors, however, we felt we were jumping into a pit of problems (as I usually feel when I start mucking around the code of real professionals). Adding in the fact that we had spent several days trying out variations of our approach with no success, we decided to go back to the drawing board and try again.

So there you have it! Our CGLibbing adventure cut short as we couldn't CGLib and a CGLibbed object. But that doesn't mean its impossible! Does anyone have any success stories? I know I skimmed a bunch of blogs and the CGLib mailing list with no success, but hopefully others have had some.

Up and Running

Alrighty! So this is my first ever blog. Kind of strange seeing as I always have my criticisms of others. Time to see how this will fair.

Stay tuned...