Java Dynamic agent and Cglib dynamic agent

Source: Internet
Author: User
Tags throwable

Dynamic agents are widely used, spring,struts and other frameworks are implemented through dynamic proxies or further encapsulation.

The common dynamic proxy pattern implementation has the dynamic proxy provided by the Java API and the third party open source class library Cglib dynamic agent.

The dynamic proxies provided by the Java API are implemented based on class reflection, and the classes used are:

Java.lang.reflect.InvocationHandler;

Java.lang.reflect.Method;

Java.lang.reflect.Proxy;

Its implementation is to generate proxy objects through the newproxyinstance () method of the proxy class. Custom dynamic proxy classes need to implement the Invocationhandler interface, which has only one invoke () method.


Cglib is to generate the proxy object dynamically by generating Java bytecode, so the dependent ASM class Library of bytecode parsing processing is needed, and the proxy object generated dynamically by bytecode actually inherits the real topic class. This implementation requires the import of Cglib and ASM class libraries. The following example is Cglib-2.2.2.jar, Asm-3.3.1.jar. Cglib uses the Methodinterceptor, the method is intercept (), which is the concept of interception, it is easy to think of the Struts2 interceptor.

In comparison, the dynamic proxy provided by the Java API needs to be interface-oriented, resulting in proxy objects, so the real-world theme implementation class must implement an interface. while Cglib does not need to interface-oriented, it can proxy simple classes , but because dynamic proxy objects are inherited from real-world theme implementations, it is not final to require a real-world theme implementation class.

The following is an example of implementation.

First of all, in order to see dynamic agents can dynamically produce different proxies based on different classes, we create a new two interface and its implementation class.

Package leon.aj.dynproxy.target;  Public interface Hello {public string SayHello (string name); }

Implementation class:

Package leon.aj.dynproxy.target; public class Helloimpl implements Hello {@Override public string SayHello (string name) {string s = "H          Ello, "+name;          System.out.println (This.getclass (). GetName () + "--" +s);      return s; }  }

Another interface and implementation class:

package leon.aj.dynproxy.target;     public interface userdao {      public boolean  login (String username,string password);   } 
Package leon.aj.dynproxy.target;           public class Userdaoimpl implements Userdao {@Override public boolean login (string username, string password) {          String user = "(" +username+ "," +password+ ")";          System.out.println (This.getclass (). GetName () + processing login: +user);      return true; }  }

Application of the Java API implementation of dynamic proxy classes:

package leon.aj.dynproxy.java;    import java.lang.reflect.invocationhandler;   import java.lang.reflect.Method;  import java.lang.reflect.Proxy;     public class JavaDynProxy implements InvocationHandler{       private Object target;      public Object  Getproxyinstance (object target) {          this.target  = target;          return  Proxy.newproxyinstance (Target.getclass (). getClassLoader (),                    target.getclass (). GetInterfaces (),  this );      }              @Override      &NBSp;public object invoke (Object proxy, method method, object[] args)                throws throwable {           Object result = null;           system.out.println ("Before target method ...");           result = method.invoke (Target, args);           system.out.println ("After target method ... ");          return result;       }  }

test:

package leon.aj.dynproxy.java;    import leon.aj.dynproxy.target.hello;   import leon.aj.dynproxy.target.HelloImpl;  import leon.aj.dynproxy.target.UserDao;   import leon.aj.dynproxy.target.UserDaoImpl;    public class  Testjavaproxy {      public static void main (String[]  args)  {          JavaDynProxy proxy =  New javadynproxy ();           hello hello =   (Hello) proxy.getproxyinstance (New helloimpl ());           string s = hello.sayhello ("Leon");           system.out.println (s);                     userdao userdao =  (Userdao)  proxy.getproxyinstance (New UserDaoImpl ());           userdao.login ("Leon",  "1234");           system.out.println (Userdao.getclass (). GetName ());       }  }

package leon.aj.dynproxy.cglib;    import java.lang.reflect.method;     import net.sf.cglib.proxy.Enhancer;  import  net.sf.cglib.proxy.methodinterceptor;  import net.sf.cglib.proxy.methodproxy;     public class CglibProxy implements MethodInterceptor {       private Object target;               public object getproxyinstance (Object target)  {             this.target = target;           enhancer enhancer = new enhancer ();             enhancer.setsuperclass (This.target.getClass ());           &nbsP; enhancer.setcallback (This);  // call back method           return enhancer.create ();  // create proxy  instance      }                @Override       public object intercept (Object  target, method method, object[] args, methodproxy proxy)  throws  Throwable {          system.out.println ("before  Target method ... ");           object result =  proxy.invokesuper (Target, args);           System.out.println ("After target method ...");           return result;      }  } 

test class:

package leon.aj.dynproxy.cglib;    import leon.aj.dynproxy.target.hello;   import leon.aj.dynproxy.target.HelloImpl;  import  leon.aj.dynproxy.target.userdaoimpl;    public class testciglib {       public static void main (String[] args)  {           cglibproxy proxy = new cglibproxy ();           Hello hello =  (Hello)   Proxy.getproxyinstance (New helloimpl ());           System.out.println (Hello.sayhello ("Leon"));           userdaoimpl userdao =  (Userdaoimpl)  proxy.getproxyinstance (New UserDaoImpl ());           userdao.login ("Leon",  " 1234 ");           system.out.println (UserDao.getClass (). Getsuperclass ());//See the parent class of the dynamic proxy instance       }  }


Java Dynamic agent and Cglib dynamic agent

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.