Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic proxy for concrete classes

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?

like image 236
eliocs Avatar asked Oct 24 '11 16:10

eliocs


People also ask

What is a dynamic proxy?

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

Is JDK a dynamic proxy?

JDK dynamic proxy is available with the JDK. It can be only proxy by interface so target class needs to implement interface. In your is implementing one or more interface then spring will automatically use JDK dynamic proxies. On the other hand, CGLIB is a third party library which spring used for creating proxy.

How does JDK dynamic proxy work?

JDK Dynamic Proxies allow one to create implementations of Java interfaces at runtime by the means of Reflection. A proxy may be seen as a subject that will forward method calls to target instances and eventually return any result produced by the target instance to the caller.

What are proxy classes in Java?

A proxy class is a class created at runtime that implements a specified list of interfaces, known as proxy interfaces. A proxy instance is an instance of a proxy class. Each proxy instance has an associated invocation handler object, which implements the interface InvocationHandler .


2 Answers

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.

like image 169
Brian Agnew Avatar answered Sep 17 '22 12:09

Brian Agnew


Unfortunately there is no such API for classes. Many frameworks are using bytecode generation libraries like CGLIB to achieve this.

like image 44
Tomasz Nurkiewicz Avatar answered Sep 20 '22 12:09

Tomasz Nurkiewicz