1. What is an agent
Proxy mode is a common Java design pattern, its 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.
2. What is dynamic proxy
When the program is running, the proxy instance object is created dynamically using the reflection mechanism. The dynamic agent mechanism of JDK can only broker the class that implements the interface , and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK.
Related classes and interfaces
// method: This method is used to generate a dynamic proxy class instance for a specified class loader, a set of interfaces, and a calling processor Static // method: The call processor is preprocessed based on these three parameters or dispatched to the delegate class instance on the launch execution object Invoke (Object proxy, method, object[] Args
3. Dynamic Proxy Example
proxy class Public classLoghandlerImplementsInvocationhandler {PrivateObject TargetObject; PublicObject Newproxyinstance (Object targetObject) { This. TargetObject =TargetObject; returnproxy.newproxyinstance (Targetobject.getclass (). getClassLoader (), Targetobject.getclass ( ). Getinterfaces (), This); } Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Start-->>" +method.getname ()); for(inti=0; i<args.length; i++) {System.out.println (args[i]); } Object ret=NULL; Try { //calling the target methodRET =Method.invoke (TargetObject, args); System.out.println ("Success-->>" +method.getname ()); }Catch(Exception e) {e.printstacktrace (); System.out.println ("Error-->>" +method.getname ()); Throwe; } returnret; }}
Interface Class Public Interface Usermanager { publicvoid addUser (String userId, String userName);
Target Class Package Com.bjpowernode.pattern; Public class Implements Usermanager { publicvoid addUser (String userId, String userName) { // System.out.println ("Start-->>adduser () userid-->>" + userId); Try { System.out.println ("AddUser" );} }}
Client Public class Client { /** @param args * / Publicstaticvoid main (string[] args) { new Loghandler ( ); = (Usermanager) loghandler.newproxyinstance (new Usermanagerimpl ()); Usermanager.adduser ("0001", " Zhang San");} }
4. The difference between a dynamic proxy class and a static proxy:
The source code is created by the programmer or generated automatically by a particular tool and then compiled. Before the program runs, the. class file for the proxy classes already exists. Dynamic Proxy classes: When the program is running, it is created dynamically using the reflection mechanism . No programmer has to write 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.
5. Application Scenarios for dynamic classes
Direct access to certain classes is not allowed, special handling is done for access, and so on. Or, you want to have a uniform extension of the original method, such as joining logging.
6. What is 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.
7.CGLIB Example
Delegate class:
Package Com.orient.cglib; Public class BOOKFACADEIMPL1 { publicvoid Addbook () { System.out.println (" An ordinary way to increase a book ... "); }
proxy class
PackageCom.orient.cglib;ImportJava.lang.reflect.Method;ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy; Public classBookfacadecglibImplementsMethodinterceptor {PrivateObject Target; /*** Create proxy Object * *@paramTarget *@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)throwsthrowable {System.out.println ("Things start."); Proxy.invokesuper (obj, args); System.out.println ("The end of things."); return NULL; } }
Test class
Package Com.orient.cglib; Public class Testcglib { publicstaticvoid main (string[] args) { Bookfacadecglib cglib=new bookfacadecglib (); BOOKFACADEIMPL1 bookcglib= (BOOKFACADEIMPL1) cglib.getinstance (new BookFacadeImpl1 ()); Bookcglib.addbook (); } }
This project relies on Cglib.jar and Asm.jar.
Java Dynamic Agent Detailed