Java Dynamic Agents (JDK and Cglib)

Source: Internet
Author: User
Tags throwable

Dynamic Agent for Java
Proxy mode
Proxy mode is a common Java design pattern, his characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.
The proxy class can be divided into two types according to the agent's creation period.
Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.
Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.

First look at the static proxy:
1, Count.java

Package Net.battier.dao;    /**  * Define an Account interface  *   * @author Administrator * */public  interface Count {      //View account method      public void Querycount ();        Modify account method public      void Updatecount ();    }  

  


2, Countimpl.java

Package Net.battier.dao.impl;    Import Net.battier.dao.Count; /** * Delegate Class (Contains business logic) * * @author Administrator * */public class Countimpl implements Count {@Override P        ublic void Querycount () {System.out.println ("View account Method ...");        } @Override public void Updatecount () {System.out.println ("Modify Account Method ...");    }}, Countproxy.java package net.battier.dao.impl;    Import Net.battier.dao.Count; /** * This is a proxy class (Enhanced Countimpl implementation Class) * * @author Administrator * */public class Countproxy implements Count {Priva        Te Countimpl Countimpl; /** * Overrides the default constructor * * @param countimpl */Public Countproxy (Countimpl Countimpl) {This.cou      Ntimpl = Countimpl;          } @Override public void Querycount () {System.out.println ("before transaction processing");          The method of invoking the delegate class;          Countimpl.querycount ();      System.out.println ("After transaction processing");  } @Override public void Updatecount () {        System.out.println ("Before transaction processing");          The method of invoking the delegate class;          Countimpl.updatecount ();        System.out.println ("After transaction processing");   }    }

  

3, Testcount.java

Package net.battier.test;    Import Net.battier.dao.impl.CountImpl;  Import Net.battier.dao.impl.CountProxy;    /**  * Test Count class  *   * @author Administrator * */Public  class Testcount {public      static void Main (string[] args) {          Countimpl Countimpl = new Countimpl ();          Countproxy countproxy = new Countproxy (COUNTIMPL);          Countproxy.updatecount ();          Countproxy.querycount ();        }  }  

  

Observation code can find that each proxy class can only serve one interface, so that the development of the program will inevitably generate too many agents, and all the agent operation in addition to the method called, the other operations are the same, then it must be duplicated code. The best way to solve this problem is to complete the proxy function through a proxy class, which must be done using dynamic proxy.
Let's take a look at the dynamic proxy:
The JDK dynamic agent contains a class and an interface:
Invocationhandler Interface:
Public interface Invocationhandler {
public object Invoke (Object Proxy,method method,object[] args) throws Throwable;
}
Parameter description:
Object proxy: Refers to the objects being proxied.
Method: Methods to invoke
object[] args: Parameters required for method invocation

The subclass of the Invocationhandler interface can be imagined as a proxy's final operation class, replacing the Proxysubject.

Proxy class:
The proxy class is an action class that specifically completes the proxy, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following operations:
public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces,
Invocationhandler h)
Throws IllegalArgumentException
Parameter description:
ClassLoader Loader: Class loader
Class<?>[] Interfaces: Get all the interfaces
Invocationhandler h: Get subclass instance of Invocationhandler interface

Ps: Class Loader
In the proxy class in the Newproxyinstance () method requires an instance of the ClassLoader class, ClassLoader actually corresponds to the class loader, in Java, there are three kinds of loaders;
Booststrap ClassLoader: This loader is written in C + + and is not visible in general development;
Extendsion ClassLoader: Used to load the extension class, generally corresponding to the class in the Jre\lib\ext directory;
Appclassloader: (default) Loads the class specified by Classpath, which is most commonly used as an loader.

Dynamic Agent
Compared with the static proxy class, dynamic proxy class, the bytecode of dynamic proxy class is generated dynamically by the Java reflection mechanism when the program runs, without the programmer writing its source code manually. The dynamic proxy class not only simplifies programming, but also improves the scalability of the software system, because the Java reflection mechanism can generate any type of dynamic proxy class. The proxy class and the Invocationhandler interface in the Java.lang.reflect package provide the ability to generate dynamic proxy classes.

Dynamic Proxy Example:
1, Bookfacade.java

Package Net.battier.dao;    Public interface Bookfacade {public      void Addbook ();  }  

  

2, Bookfacadeimpl.java

Package Net.battier.dao.impl;    Import Net.battier.dao.BookFacade; public class Bookfacadeimpl implements Bookfacade {@Override public void Addbook () {System.out.prin Tln ("Add Book Method ...      ");    }}, Bookfacadeproxy.java package net.battier.proxy;  Import Java.lang.reflect.InvocationHandler;  Import Java.lang.reflect.Method;    Import Java.lang.reflect.Proxy;  /** * JDK Dynamic Proxy proxy class * * @author Student * */public class Bookfacadeproxy implements Invocationhandler {private      Object Target; /** * Binds the delegate object and returns a proxy class * @param target * @return */Public Object bind (object target) {th          Is.target = target; Gets the proxy object return Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Get   Interfaces (), this); To bind the interface (this is a flaw, cglib compensates for this flaw)} @Override/** * Call method */Public object Invoke (object proxy, method, object[] args) tHrows throwable {Object result=null;          System.out.println ("things start");          Execution method Result=method.invoke (target, args);          System.out.println ("End of Thing");      return result;   }    }

  

3, Testproxy.java

Package net.battier.test;    Import Net.battier.dao.BookFacade;  Import Net.battier.dao.impl.BookFacadeImpl;  Import Net.battier.proxy.BookFacadeProxy;    public class Testproxy {public        static void Main (string[] args) {          Bookfacadeproxy proxy = new Bookfacadeproxy (); 
   bookfacade bookproxy = (bookfacade) proxy.bind (New Bookfacadeimpl ());          Bookproxy.addbook ();      }    }  

  

However, the dynamic proxy of the JDK relies on the interface, and if some classes do not implement the interface, then the JDK proxy cannot be used, which will use the Cglib dynamic proxy.

Cglib Dynamic Agent
The dynamic agent mechanism of JDK can only implement the class of the interface, and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK, the cglib is to implement the proxy for the class, his principle is to generate a subclass for the target class, and overwrite the method implementation enhancement, but because inherit is adopted, Therefore, the final decorated class cannot be proxied.
Example
1, Bookfacadecglib.java

Package Net.battier.dao;    Public interface Bookfacade {public      void Addbook ();  }  

  

2, Bookcadeimpl1.java

Package Net.battier.dao.impl;    /**  * This is an implementation class that does not implement an interface  *   * @author Student * */public  class BookFacadeImpl1 {public      void Addbook () {          System.out.println ("general method of adding books ...");}  }  

  


3, Bookfacadeproxy.java

Package net.battier.proxy;    Import Java.lang.reflect.Method;  Import Net.sf.cglib.proxy.Enhancer;  Import Net.sf.cglib.proxy.MethodInterceptor;    Import Net.sf.cglib.proxy.MethodProxy; /** * Use cglib dynamic agent * * @author Student * */public class Bookfacadecglib implements Methodinterceptor {privat        e Object target;          /** * Create proxy Object * * @param target * @return */public object getinstance (object target) {          This.target = target;          Enhancer enhancer = new enhancer ();          Enhancer.setsuperclass (This.target.getClass ());          Callback method Enhancer.setcallback (this);      Create proxy object return Enhancer.create (); } @Override//callback method public Object intercept (object obj, Method method, object[] args, method          Proxy) throws Throwable {System.out.println ("things start");          Proxy.invokesuper (obj, args);          System.out.println ("End of Thing");      return null; }  }  

  


4, Testcglib.java

Package net.battier.test;    Import NET.BATTIER.DAO.IMPL.BOOKFACADEIMPL1;  Import Net.battier.proxy.BookFacadeCglib;    public class Testcglib {public            static void Main (string[] args) {          bookfacadecglib cglib=new bookfacadecglib (); C5/>BOOKFACADEIMPL1 bookcglib= (BOOKFACADEIMPL1) cglib.getinstance (New BookFacadeImpl1 ());          Bookcglib.addbook ();      }  }  

  

Java Dynamic Agents (JDK and Cglib)

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.