Java Dynamic Agents (JDK and Cglib)

Source: Internet
Author: User
Tags throwable

Java's dynamic agent 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 InterfaceCount {//View account Methods     Public voidQuerycount (); //Modify Account Method     Public voidUpdatecount (); }  2, Countimpl.java package net.battier.dao.impl;    Import Net.battier.dao.Count; /** * Delegate class (Contains business logic) * * @author Administrator **/   Public classCountimpl implements Count {@Override Public voidQuerycount () {System. out. println ("View Account Method ..."); } @Override Public voidUpdatecount () {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 classCountproxy implements Count {PrivateCountimpl Countimpl; /** * Override default Constructor * * @param countimpl*/       Publiccountproxy (Countimpl countimpl) { This. Countimpl =Countimpl; } @Override Public voidQuerycount () {System. out. println ("before transaction processing"); //the method of invoking the delegate class; Countimpl.querycount (); System. out. println ("after transaction processing"); } @Override Public voidUpdatecount () {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 classTestcount { Public Static voidMain (string[] args) {Countimpl Countimpl=NewCountimpl (); Countproxy Countproxy=NewCountproxy (Countimpl);          Countproxy.updatecount ();        Countproxy.querycount (); }} The observation code can be found 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 is definitely a duplicate 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 InterfaceInvocationhandler { Publicobject 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: The parameters required by the method call can imagine the subclass of the Invocationhandler interface as the final action class of an agent, replacing the proxysubject. Proxy class: proxy class is specialized to complete the operation of the agent class, you can use this class for one or more interfaces to dynamically generate the implementation class, this class provides the following operation methods: Public StaticObject newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) throws illegalargumentexception parameter description: ClassLoader l Oader: ClassLoader class<?>[] Interfaces: Get all interfaces Invocationhandler H: Get the subclass instance of the 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 uses C++written, is not seen in general development; Extendsion ClassLoader: Used to load the extended 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 Proxy is the dynamic proxy class compared with Static proxy class, and 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 InterfaceBookfacade { Public voidAddbook (); }   2, Bookfacadeimpl.java package net.battier.dao.impl;    Import Net.battier.dao.BookFacade;  Public classBookfacadeimpl implements Bookfacade {@Override Public voidAddbook () {System. out. println ("increase the 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 classBookfacadeproxy implements Invocationhandler {PrivateObject Target; /** * Bind the delegate object and return a proxy class * @param target * @return*/       Publicobject bind (object target) { This. target =Target; //Get proxy Object        returnproxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), This);//to bind an interface (this is a flaw, cglib compensates for this flaw)} @Override/** * Call method*/       Publicobject Invoke (Object proxy, Method method, object[] args) throws Throwable {object result=NULL; System. out. println ("things start"); //Execution Methodresult=Method.invoke (target, args); System. out. println ("The end of things"); returnresult; }    }   3, Testproxy.java package net.battier.test;  Import Net.battier.dao.BookFacade;  Import Net.battier.dao.impl.BookFacadeImpl;    Import Net.battier.proxy.BookFacadeProxy;  Public classTestproxy { Public Static voidMain (string[] args) {Bookfacadeproxy proxy=NewBookfacadeproxy (); Bookfacade Bookproxy= (Bookfacade) proxy.bind (NewBookfacadeimpl ());      Bookproxy.addbook (); However, the dynamic proxy of the JDK relies on the interface implementation, 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 JDK dynamic agent mechanism can only broker the implementation of the interface class, and cannot implement the interface of the class can not implement the dynamic agent of the JDK, Cglib is to implement the proxy for the class, his principle is to create a subclass of the specified target class, and override the method implementation enhancements, but because the use of inheritance , the final decorated class cannot be proxied. Example1, Bookfacadecglib.java package Net.battier.dao;  Public InterfaceBookfacade { Public voidAddbook (); }   2, Bookcadeimpl1.java package net.battier.dao.impl; /** * This is an implementation class that does not implement an interface * * @author student **/   Public classBOOKFACADEIMPL1 { Public voidAddbook () {System. out. println ("an ordinary way to add 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 classBookfacadecglib implements Methodinterceptor {PrivateObject Target; /** * Create proxy Object * * @param target * @return*/       Publicobject GetInstance (object target) { This. target =Target; Enhancer Enhancer=Newenhancer (); Enhancer.setsuperclass ( This. Target.getclass ()); //callback MethodEnhancer.setcallback ( This); //Create a proxy object        returnenhancer.create (); } @Override//callback Method     PublicObject Intercept (Object obj, Method method, object[] args, Methodproxy proxy) throws Throwable { System. out. println ("things start");          Proxy.invokesuper (obj, args); System. out. println ("The end of things"); return NULL; }    }  4, Testcglib.java package net.battier.test;  Import NET.BATTIER.DAO.IMPL.BOOKFACADEIMPL1;    Import Net.battier.proxy.BookFacadeCglib;  Public classTestcglib { Public Static voidMain (string[] args) {bookfacadecglib cglib=NewBookfacadecglib (); BOOKFACADEIMPL1 Bookcglib= (BOOKFACADEIMPL1) cglib.getinstance (NewBookFacadeImpl1 ());      Bookcglib.addbook (); }  }  

Http://www.cnblogs.com/jqyp/archive/2010/08/20/1805041.html

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.