Java Proxy Class
Java has 2 kinds of proxy,
I will introduce them one by one. But for demonstrating usage, I need to declare several java bean here.
These 2 classes are common ones for later tests.
Static proxy means to build the proxy before runtime, so static proxy class needs to be compiled for usage. In addition, static proxy needs to implement all involved proxyed methods, which is really painful.
Quite straight forward, static proxy is a simple wrapper that implements the same interface.
But be aware, you need to implement all method for wrapping one class. This is reall tedious, especially if all wrapping functions are the same.
Dynamic proxy means to proxy methods during runtime. Dynamic proxy need to setup only one method for encapsulating. But for the convenience, performance is sacrificed. Dynamic proxy is 100 times slower than static one.
Actually there are two dynamic proxies: one is the Java supported interface way, another is CGlib based. I will showcase them later on.
One thing I need to emphasis here is, even though I wrote subsection name with
Code Generation, they both utimately achieve proxy function by byte code generation.
Still, Different way of dynamic proxying has different restriction, choose the best one to fit your project.
In Java reflection supported dynamic proxy solution, the proxyed class has to implement one interface named
As you can see, class want to be proxied has to implement
InvocationHandler interface. This is the only restriction of Java Reflection supported dynamic proxy.
But because we could only proxy interface implemented classes, we are unable to make use of this method in some cases.
So to solve this problem, CGLib provisioned another way to proxy dynamically.
subclass of the target, this dynamic proxy method now could proxy any class except those with
In this instance we build a class that implements a CGLib interface
MethodInterceptor, but now we could proxy any
not final classes by using this proxy class.