Simply put, the proxy pattern is to add a layer of proxy objects between the target object and the Access object, and all the Access objects implement the call to the target object through the proxy object.
The proxy object and the target object implement the same interface, and the proxy object invokes the target object, and for the outside, the proxy object can override the target object being called. In this way, the proxy object can add additional logic to normal access, such as caching, permission control, logging, and so on.
But this static proxy mode needs to add additional proxy class implementation, Java 5 began to introduce a dynamic agent mechanism, implemented at runtime to create a proxy object dynamically, which is actually a method call interception, AOP is the use of this model.
Examples of use of dynamic proxies
| 1 |
<span style="font-size:16px;">packagecom.dynamic.jdk;<br><br>/**<br> * 目标类的接口定义<br> * <p/><br> * Created by Vincent Tse on 12/2/15.<br> */<br>public interface MyInterface {<br> voiddoSomething();<br>}<br></span> |
| 1 |
<span style="font-size:16px;">packagecom.dynamic.jdk;<br><br>/**<br> * 目标类的具体实现<br> * <p/><br> * Created by Vincent Tse on 12/2/15.<br> */<br>publicclassMyInterfaceImpl implementsMyInterface {<br><br> @Override<br> publicvoiddoSomething() {<br> System.out.println("here is my real operation!");<br> }<br>}<br></span> |
| 1 |
<span style="font-size:16px;">packagecom.dynamic.jdk;<br><br>importjava.lang.reflect.InvocationHandler;<br>importjava.lang.reflect.Method;<br><br>/**<br> * 自定义的InvocationHandler<br> * 封装具体的调用过程<br> * <p/><br> * Created by Vincent Tse on 12/2/15.<br> */<br>publicclassMyInvocationHandler implementsInvocationHandler {<br> Target is the object that actually executes the method <br> private object target;<br><br> public Myinvocationhandler (Object target) {<br> super ();<br> This.target = target;<br> }<br><br> /**<br> * Method of proxy object invocation & lt;br> * @param proxy<br> * @param method<br> * @param args<br > * @return <br> * @throws throwable<br> */<br> &NBSP ; @Override <br> public object Invoke (Object proxy, Method method, object[] args) throws Throwable {<b r> &NBSP;SYSTEM.OUT.PRINTLN ("before Target ' s operation!"); <br> object result = Method.invoke (target, args);<br> sy STEM.OUT.PRINTLN ("After Target ' s operation");<br> return result;<br> }<br>}<br></span> |
| 1 |
<span style="font-size:16px;">packagecom.dynamic.jdk;<br><br>importjava.lang.reflect.Proxy;<br><br>/**<br> * 测试类<br> * <p/><br> * Created by Vincent on 12/2/15.<br> */<br>publicclassDynamicTest {<br><br> publicstaticvoidmain(String[] args) {<br><br> //生成目标对象<br> MyInterface myInterface = new MyInterfaceImpl();<br><br> //实例化invocationHandler对象,传入目标对象作为target<br> MyInvocationHandler invocationHandler = new MyInvocationHandler(myInterface);<br><br> //调用Proxy的方法生成代理对象<br> MyInterface proxy = (MyInterface)Proxy.newProxyInstance(myInterface.getClass().getClassLoader(),<br> new Class[]{MyInterface.class}, invocationHandler);<br><br> //调用代理对象的方法<br> proxy.doSomething();<br> }<br>}<br></span> |
Output Result:
Before Target ' s operation!
Here is my real operation!
After Target ' s operation!
Easy to use, then see the source code analysis of the Principles
Starting with the Newproxyinstance () method of proxy, this method is used to generate the proxy object, which needs to pass in the ClassLoader, the implemented interface, and a Invocationhandler object.
| 1 |
<span style="font-size:16px;">publicstatic Object newProxyInstance(ClassLoader loader,<br> Class<?>[] interfaces,<br> InvocationHandler h)<br> throwsIllegalArgumentException<br>{<br> Objects.requireNonNull(h);<br><br> finalClass<?>[] intfs = interfaces.clone();<br> final SecurityManager sm = System.getSecurityManager();<br> if(sm != null) {<br> checkProxyAccess(Reflection.getCallerClass(), loader, intfs);<br> }<br><br> Generate proxy classes by passing in the class loader and implementing interfaces <br> Class<?> cl = GETPROXYCLASS0 (loader, intfs);<br><br> & nbsp /*<br> * Invoke its constructor with the designated invocation handler.<br> */<br> try {<br> if (SM! = null) {<br> &NBS P checknewproxypermission (Reflection.getcallerclass (), cl);<br> &NBSP;}<BR > //reflection gets the constructor of the proxy class <br> fin Al constructor<?> cons = Cl.getconstructor (constructorparams);<br> final Invocationhandler ih = h;<br> &NBSP;IF (! Modifier.ispublic (Cl.getmodifiers ())) {<br> Accesscontroller.doprivileged (New privilegedaction<void> () {<br> &nbSp public Void Run () {<br> &NBSP;CONS.SETACCESSIBL E (true);<br> return null;<br> &nbs P }<br> });<br> }<br> //reflection generation instance, passing Invocationhandler in, then invoking the Invoke method depends on it <br> & nbsp return cons.newinstance (New object[]{h});<br> } catch (illegalaccessexception| Instantiationexception e) {<br> throw new Internalerror (E.tostring (), E);<br> & nbsp } catch (InvocationTargetException e) {<br> throwable t = e.getcause ();<br> & nbsp if (t instanceof runtimeexception) {<br> throw (Runtime Exception) t;<br&Gt } else {<br> throw new Internalerror (T.tostring ( ), T);<br> }<br> } catch (Nosuchmethodexception e) {<br> throw New Internalerror (E.tostring (), E);<br> }<br>} <br></span > |
GetProxyClass0 () method is used to generate the proxy class, first check the implementation of the number of interfaces, more than 65535 to throw an exception, the sense should not have implemented so many interfaces of the class bar.
| 1 |
<span style="font-size:16px;">privatestaticClass<?> getProxyClass0(ClassLoader loader,<br> Class<?>... interfaces) {<br> if(interfaces.length > 65535) {<br> thrownewIllegalArgumentException("interface limit exceeded");<br> }<br><br> //从一个Cache中获取代理类,如果没有就重新生成<br> return proxyClassCache.get(loader, interfaces);<br>}<br></span> |
Proxyclasscache is a static weakcache, defined in the proxy class.
Weakcache has two factory, one is subkeyfactory, Java Training is a mapping function (key, parameter)->sub-key, and the other is valuefactory, is a mapping function (key, parameter)->value. The Get method of Weakcache requires two parameters, one is key and the other is parameter.
The use and principle of specific weakcache is not mentioned here, please refer to the source code.
| 1 |
<span style= "FONT-SIZE:16PX;" > private static final weakcache<classloader, class<?>[ ], class<?>><br> proxyclasscache = new weakcache<> ( new keyfactory (), new Proxyclassfactory ()); <br></span> |
The incoming keyfactory and proxyclassfactory are static classes defined in the proxy class, respectively, corresponding to the subkeyfactory and valuefactory in the Weakcache, which implements the Bifunction interface. and implement the Apply () method. What is done in Proxyclassfactory's apply () method is to generate the logic of the proxy class, and most crucially
| 1 |
<span style="font-size:16px;">byte[] proxyClassFile = ProxyGenerator.generateProxyClass(<br> proxyName, interfaces, accessFlags);<br></span> |
The above method is used to generate the byte code of the proxy class, the proxy class will have an interface implementation method, in the implementation of the method will invoke the Invocationhandler invoke () method, interested in the generated bytecode can be written to the local, with the anti-compilation tool to open the look.
So Proxyclassfactory's apply () method is called when, back to Weakcache's Get () method
| 1 |
<span style="font-size:16px;">Generate subkey to get the corresponding Supplier<br>object subkey = Objects.requirenonnull (Subkeyfactory.apply (key, parameter));< br>supplier<v> Supplier = Valuesmap.get (subkey); <br>factory Factory = null;<br>//has been circulating, Until value is obtained from supplier <br>//if no supplier is generated factory and added to the cache (source says this is an install process) <br>while (true) {<BR > &NBSP;IF (supplier! = NULL) {<br> &NBSP;V value = Supplier.get ();<br> &NBSP;IF (value = null) {<br> return value;<br> }<br> }<br> <br> if (factory = = null) {<b r> //factory is an internal class that implements the supplier interface and implements the Get () method <br> //actually in the get () method calls the Apply () method of valuefactory (that is, proxyclassfactory) <br> //can debug in to see <br> factory = new factory (key, parameter, SubkeY, Valuesmap);<br> }<br><br> if (supplier = = NULL) {<br> & nbsp supplier = Valuesmap.putifabsent (subkey, Factory);<br> if (supplier = null) {< br> supplier = factory;<br> }<br>   ; } else {<br> &NBSP;IF (Valuesmap.replace (subkey, supplier, Factory)) {<br> & nbsp supplier = factory;<br> } else {<br> &NBSP ; supplier = Valuesmap.get (subkey);<br> }<br> } <br>}<br></span> |
Good hard, finally generated the proxy class, back to the Newproxyinstance method, with the class object of the proxy classes, you can generate an instance by reflection (called the constructor with the Invocationhandler parameter), after the generation of the instance can be used proxy object.
Java Dynamic Agent