JDK dynamic agent and runtime weave byte code

Source: Internet
Author: User
Tags aop reflection

Java JDK Dynamic agent is actually a dynamic generation of bytecode and reflection mechanism of a combination, when it comes to reflection mechanism a lot of people have used the reflection, as long as the corresponding classes of class object can be, call methods, get member variables and so on, then the JDK dynamic agent is in the process of running the program, Dynamic will we maintain the inspection of code, before the normal business code, then how to call my normal business code, because there may be many kinds of business, that is, there may be different classes, but all have to execute the same check code, such as we want to withdraw money, or modify the identity card, must be verified by the CAN, This is obviously two classes, one is money, one is the ID, so when we call the normal business code, we actually do not know who we call the code, this time to use the reflection, through reflection, dynamic recognition type, and then call the method, such as we want to withdraw money, Then the incoming should be a money instance, through this instance of the Getdeclaredmethod, or getmethod can be, get the corresponding instance of the method, and then you can dynamically invoke the method, as long as the reflection before, add our verification code can be, This is reflected in the application of the dynamic agent. This part of the code needs our own implementation of the Invocationhandler interface, the implementation of the Invoke method, in this method, is our implementation of the above reflection. Of course, in order to invoke the method of the corresponding class, we implement the Invocationhandler class, we need to save an instance of our proxy class.

And the dynamic generation of bytecode is a technology, that is, in the compilation period can not determine the type of bytecode to generate, that is, no corresponding Java files, so you can not generate class files, like a static proxy, we will explicitly implement a proxy class, so you can generate a bytecode file at compile time, But the dynamic agent does not explicitly implement a class of proxy class, is a common class for all business classes, because at compile time cannot decide to generate that business class proxy class so can not generate bytecode, but at run time, see our incoming instance is what class input, generate the corresponding class of proxy class, Because this time to determine the generation of a proxy class, if there is no bytecode file, then the class will not be loaded, more will not be executed, so the dynamic agent technology, the bytecode file will be dynamically stitched out to form a class file, which is the dynamic generation of byte code files. This technique is implemented in a Java class.

Proxy static method, Newproxyinstance (), this method has three parameters, the first parameter is the class loader of the proxy class (ClassLoader), the second parameter is the proxy class of all interfaces, The third parameter is our implementation class (Invocationhandler) instance, then this method, return is a proxy class, that is, in this method, the dynamic splicing proxy class byte code.

Dynamic agents have two main applications: the first is if the code in many places will use the same code, such as security check, permission validation, in the very business module will be used, usually placed in the head of our business code or the tail, then if not the dynamic agent, the same code will be scattered in the various parts of your program , first of all, the code taking rate is too poor, next is the maintainability is not high, if you want to change the way you access authentication, then you need in the program every place to change, so it will be difficult to maintain, simply we will all the inspection of code, all extracted, together maintenance, such code maintenance together, then it is quite convenient, This is the aspect-oriented programming that is AOP, we put the inspection of code in a class to maintain together, then this class is called the tangent. The concept of AOP will be widely used in spring, such as the life-style transaction in spring, which is implemented with AOP, dynamically adding transactions to database operations, and the second major application, which is an application similar to an interceptor, which is preceded by your business code, plus the code of inspection, If you pass then execute your business code, if you do not pass then do not execute your business code. In fact, this is not fully used in dynamic agents, mainly with dynamic proxy reflection in the implementation part, in the actual application will generally use the interceptor stack, which is a series of interceptors, that is to check multiple legitimacy, an interceptor verification through the next interceptor, when all the interceptor verification passed, is the real business code. This idea in fact is the design mode of the responsibility chain mode, in the SPRINGMVC there will be a great application, below I simply manually implemented an interceptor (not the interceptor stack), which is both an interceptor, but also a dynamic agent application, I hope to help you, here is my code.


Although the JDK's dynamic agent was used before, some problems have not been understood.      For example, the Invocationhandler invoke method is called by WHO, the proxy object is generated, until the first few weeks to understand all these problems. Needless to say, let's take a look at how the JDK's dynamics are used.

Java code    package dynamic.proxy;       import  java.lang.reflect.invocationhandler;   import java.lang.reflect.method;   import  java.lang.reflect.proxy;     /**   *  implement your own invocationhandler   *   @author  zyb   *  @since  2012-8-9   *   */   Public  class MyInvocationHandler implements InvocationHandler {               //  target Objects         private  Object target;              /**       *  Construction methods        *  @param  target  Target Objects         */       public  Myinvocationhandler (Object target)  {           super ();            this.target = target;       }              /**       *  ways to execute target objects         */       public object invoke (object proxy ,  method method, object[] args)  throws Throwable {                       //  Simply print a bit before the method of the target object is executed            system.out.println ("----------- -------before------------------");                      //  methods for executing target objects            &nbSp;object result = method.invoke (Target, args);                       //  Simply print after the method of the target object is executed            system.out.println ("------------------- After------------------");                       return result;       }           /**       *  get proxy objects for target objects         *  @return   Proxy objects        */        public object getproxy ()  {            Return proxy.newproxyinstance (Thread.CurrentThread (). Getcontextclassloader (),          &Nbsp;          target.getclass (). GetInterfaces (),  this) ;       }  }      package dynamic.proxy;      /**   *  target object implementation interface, using JDK to generate proxy objects be sure to implement an interface    *  @author  zyb    *  @since  2012-8-9   *   */   public interface  userservice {          /**       *   Target methods         */       public abstract  void add ();     }      package dynamic.proxy;       /**   *  target objects  

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.