Dynamic proxy for concrete classes

eliocs picture eliocs · Oct 24, 2011 · Viewed 11.6k times · Source

I want to define a method interceptor in a Java program in other words I want to have a behaviour which is executed at each method call. This application isn't executed in an application server and therefore I can't use the EJB around invoke interceptors. I have found a nice Proxy API in the standard Java libraries but its limited because it needs an interface in the proxy creation:

 Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                                      new Class[] { Foo.class },
                                      handler);

Is there a similar API which doesn't force Foo.class to be declared as an interface?

Answer

Brian Agnew picture Brian Agnew · Oct 24, 2011

Why not use CGLIB ? See this article for more information.

What if you want to proxy legacy classes that do not have interfaces? You can use CGLIB. CGLIB is a powerful, high-performance code generation library. Under the cover, it uses ASM, a small but fast bytecode manipulation framework, to transform existing byte code to generate new classes. CGLIB is faster than the JDK dynamic proxy approach. Essentially, it dynamically generates a subclass to override the non-final methods of the proxied class and wires up hooks that call back to the user-defined interceptors.