Java Proxy Class
Introduction
Java has 2 kinds of proxy, static
and dynamic
.
I will introduce them one by one. But for demonstrating usage, I need to declare several java bean here.
1 |
|
These 2 classes are common ones for later tests.
Static Proxy
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.
1 |
|
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.
1 |
|
Dynamic Proxy
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
Java Reflection
andCode 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.
Java Reflection
In Java reflection supported dynamic proxy solution, the proxyed class has to implement one interface named InvocationHandler
.
1 |
|
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.
1 |
|
But because we could only proxy interface implemented classes, we are unable to make use of this method in some cases.
Code Generation
So to solve this problem, CGLib provisioned another way to proxy dynamically.
By generating subclass
of the target, this dynamic proxy method now could proxy any class except those with final
ones.
1 |
|
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.
1 |
|