Javassist. What is the main idea and where real use?

user471011 picture user471011 · Sep 4, 2011 · Viewed 12.5k times · Source

I know that Javassist is a Java library providing a means to manipulate the Java bytecode of an application.

Ok, but why we need manipulate bytecode?

Any real example? Any real app, where javassist used?

Answer

meriton picture meriton · Sep 4, 2011

A common application is to generate proxy classes at runtime, i.e. to create a subclass at runtime that intercepts all method invocations. Examples:

Hibernate uses Proxies to intercept method invocations on entities to implement lazy loading, i.e. fetching the object from the database when it is first accessed.

The Spring Framework uses Proxies to implement its AOP support, which among other things powers its support for declarative transactions. It also uses proxies to enforce proper scoping.

EJB uses proxies to implement container managed transactions, authorization checking, and to apply user-defined interceptors.

CDI implementations must also proxy the managed beans to ensure proper scoping. I suspect they use a byte code engineering library, too.

I recently used Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.

Note that java.lang.reflect.Proxy can generate proxy classes at runtime, but can only implement interfaces, not extend a class. All of the above use cases require the proxying of classes.