sixlegs.com / blog / java / cglib-lazy-loading.html

Root Beer Logo Root Beer

Chris Nokleberg's Fizzy Weblog

April 2003
Su M Tu W Th F Sa
    3 5
6 7 8 10 11 12
14 15 16 17 19
20 21 22 23 24 25 26
27 28 29 30
Previous  |  Next  |  More...
#  Lazy Loading with CGLIB

I've written a lot of code for CGLIB but have been less than diligent about documentation. Hopefully this blog will keep me motivated to write and some of the content will make it into javadoc.

The original and still most important class in CGLIB is the Enhancer. It is a substitute for the standard Dynamic Proxy support, but with some important differences, including:

  • Runs on JDK 1.2.
  • Can proxy (almost) any class, not just interfaces.
  • Less overhead on intercepted calls.

The Enhancer class is probably best suited to integration within a larger framework, but I have run into one-off cases where it has come in very handy. One example is the ServletResponse API, which specifies that once you call getOutputStream or getWriter, calling the other will result in an exception. For my project I needed to hand off both objects to another method, which could then decide for itself which one to use. Changing the API to support passing in a ServletRequest was not an option. Dynamic Proxies would not work here since OutputStream and Writer are classes, not interfaces.

This code does the trick. It creates a new OutputStream that has all public methods intercepted, and only gets the actual OutputStream from the response once any of the intercepted methods is called. Hibernate uses CGLIB in a similar way to lazily load entities from the database.

[Powered By FreeMarker]  [Valid Atom 1.0]  [Weblog Commenting by HaloScan.com]