Sunday, February 02, 2014

What is Javaassist?

Javaassist stand for Java Programming Assistance. It's java library providing means to manipulate java bytecode. 
  • It enables java program to create new java classes at runtime and to modify classes before JVM loads it.
  • It's sub project of Jboss.

Now Question is "Why we require to manipulate java bytecode"?
  • You want to create subclasses at runtime which intercepts methods invocations. Meaning "Generating Proxies" which intercepts methods invocations.
  • Hibernate uses proxies to intercept methods invocation on entities to implement lazy loading. ie. fetching objects from database once it's accessed. 
  • Spring also uses proxies to implement it's AOP Support. 

We should know :
  • There are many third parties libaries like Javaassist, CGLib, ASM etc but I perfer Javaassist.
  • It seems that Hibernate 3.6 deprecated CGlib for some reasons. Hibernate 3.6 Deprecated List  shows that support for cglib as bytecode provider has been deprecated.
  • Difference between JDK Dynamic Proxy and Cglib/javaasssit is that JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which will also be implemented by the proxy class).CGLIB and javassist can create a proxy by subclassing. Here, proxy becomes a subclass of the target class. No need for interfaces.
    So Java Dynamic proxies can proxy: public class Aimplements iA where CGLIB can proxy: public class A

You can use following dependencies for  Javaassist in pom.xml:

  javassist
  javassist
  3.12.1.GA


For More Details Visit:

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment