Java implements AOP using dynamic proxies

Source: Internet
Author: User
Tags aop throwable

Resources:

Http://www.importnew.com/15420.html
Http://www.cnblogs.com/techyc/p/3455950.html

Spring is the use of dynamic agents (JDK dynamic proxy) and Cglib two technologies to implement AOP, this article will learn from previous examples using dynamic agents to simulate the characteristics of AOP.

1. Environment

java:jdk1.8.0_144

2. Learning dynamic proxy proxy.newproxyinstance () method

Its three parameters are as follows

Name of parameter Type Description
Loader ClassLoader class loader for proxy class
Interfaces Class<?>[] Interface collection implemented by the proxy class
H Invocationhandler All method calls to the proxy class are bound to the Invoke method of the Java.lang.reflect.InvocationHandler interface to execute

3. Realization of Ideas

    • Proxy target object via JDK dynamic proxy
    • Overrides the Invoke method of the Invocationhandler, wraps the method call of the proxy object, dynamically adds logic to implement the AOP function similar to After/before/around

To some extent, the idea of implementation is similar to the adorner pattern, which differs from

    • The wrapper class in the adorner pattern needs to know the interface details of the wrapped class, and there is no need to
    • The adorner mode does not need to use reflection and proxy, and this requires

4. Code parsing

Https://github.com/hivsuper/study/tree/master/study-aop

    • The class and its interfaces that will be proxied
 Public Interface Calculator {    publicint Add (intint  b);}
 Public class Implements Calculator {    @Override    publicint Add (intint  b) {         return a + B;    }}
    • Binding the dispatch interface of the Proxied object
 import   Java.lang.reflect.InvocationHandler;  public  abstract  class  Abstracthandler implements   Invocationhandler {
    private   Object TargetObject;  public   Object Gettargetobject () {    Span style= "COLOR: #0000ff" >return   TargetObject;  public  void   Settargetobject (Object targetObject) { this . TargetObject = TargetObject; }}
    • Simple factory for generating agents
ImportJava.lang.reflect.Proxy;Importjava.util.List; Public classProxyfactory { Public StaticObject GetProxy (Object TargetObject, list<abstracthandler>handlers) {Object Proxyobject=NULL; if(Handlers.size () > 0) {Proxyobject=TargetObject;  for(Abstracthandler abstracthandler:handlers) {abstracthandler.settargetobject (proxyobject); Proxyobject=proxy.newproxyinstance (Targetobject.getclass (). getClassLoader (), Targetobject.getclass (). getIn            Terfaces (), Abstracthandler); }            returnProxyobject; } Else {            returnTargetObject; }    }}
    • Test class
ImportJava.lang.reflect.Method;Importjava.util.ArrayList;Importjava.util.List;ImportOrg.junit.Assert;Importorg.junit.Test;ImportOrg.lxp.study.aop.AbstractHandler;Importorg.lxp.study.aop.ProxyFactory; Public classcalculatorimpltest {@Test Public voidTestadd ()throwsException {Calculator Calculator=NewCalculatorimpl (); Abstracthandler before=NewAbstracthandler () {@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("... before ..."); returnMethod.invoke (Gettargetobject (), args);        }        }; Abstracthandler After=NewAbstracthandler () {@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {Object result=Method.invoke (Gettargetobject (), args); System.out.println ("... after ..."); returnresult;        }        }; Abstracthandler around=NewAbstracthandler () {@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {StringBuilder sb=NewStringBuilder ();  for(Object Arg:args) {sb.append (ARG). Append (","); } System.out.println ("Parameters:" + sb.substring (0, Sb.length ()-1)); Object result=Method.invoke (Gettargetobject (), args); System.out.println ("Result:" +result); returnresult;        }        }; List<AbstractHandler> handlers =NewArraylist<abstracthandler>();        Handlers.add (before);        Handlers.add (after);        Handlers.add (around); Calculator Proxy=(Calculator) proxyfactory.getproxy (Calculator, handlers); Assert.assertequals (Proxy.add (20, 10)); }}

Java implements AOP using dynamic proxies

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.