Talking about the knowledge of Java proxy pattern two

Source: Internet
Author: User

Let's go on to the static agent of the previous blog to start today's dynamic agent.

First, dynamic agent

The static proxy needs to write the proxy class before running, which causes a lot of duplication of the code, so we dynamically generate the proxy class of the business class by dynamic proxy at runtime, so how is the dynamic proxy class implemented?

The bytecode of the dynamic proxy class is dynamically generated by the Java reflection mechanism when the program is run, 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. The original is to use the mechanism of reflection to achieve, today we do not discuss reflection, we look at the JDK dynamic agent implementation.

      the JDK dynamic Agent contains a class and an interface:  invocationhandler interface, and we define an implementation class "Proxy", which is a universal proxy class, we are through this proxy class to dynamic proxy.
      Invocationhandler interface:  
       Public interface Invocationhandler { 
      public Object Invoke (object proxy, Method method,object[] args) throws throwable; 
     } 
       parameter description:  
           object proxy: Refers to the object being proxied.  
           method:   to invoke;
           object[] args: Parameter   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 agent, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following methods of Operation: 
     public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h)  
                                throws illegalargumentexception 
      parameter description:  
            ClassLoader Loader: class loader  
           Class<?>[] Interfaces: Get all the interface  
           Invocationhandler h: Gets 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 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.
ii. Dynamic agents using the JDK

or using the code of the previous blog, we are also simple to say three steps to achieve: business interface, the creation of business implementation class, the creation of proxy classes, business calls.

Let's look at the code implementation:

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/**     * Define a business interface       * @author Cassie       *        /public interface Account {            //query public           void Queryaccount ();                Modify public            void Updateaccount ();          }          /**       * Interface Implementation class (contains business logic)       *  i.e.: Delegate class      * @author Cassie */public        class Accountimpl implements account{                    @Override public            void Queryaccount () {                System.out.println ("Query method ...");                    @Override public            void Updateaccount () {                System.out.println ("Modify Method ...");}                } </span>

The key dynamic agent is the following lines of code: The proxy class Proxy does not implement a specific business interface, but implements the Invocationhander class provided by the JDK. In the proxy we do not need to know the specific business class, that is, the delegate class, before running, the delegate class and the proxy class to decouple, in the run-time only occurs in the connection, is through this sentence to achieve: private object target. And then at the time of the call through getinstance in determining who is the delegate object.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/**  * JDK Dynamic Proxy proxy class  *   * @author Cassie * */public  class Proxy implements Invocationhandler {      Private Object target;      /**      * Binds the delegate object and returns a proxy class      * @param target      * @return */public      Object getinstance (object target) {          this.target = target;          Get the proxy object          return Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces ( ), this);       }        @Override      /**      * Call Method      *      /public object Invoke (object proxy, Method method, object[] args)              Throws Throwable {          Object result=null;          System.out.println ("before");          Execution method          Result=method.invoke (target, args);          System.out.println ("after");          return result;      }    } </span>

Then look at our client invocation: This is the time to pass in the real delegate class.

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >public class Testproxy {public        static void Main (string[] args) {          proxy proxy = new Proxy ();  Here is the real object incoming account        account= (account) proxy.getinstance (new Accountimpl ());          Proxy.queryaccount ();      }    } </span>

The above process is the implementation of the JDK dynamic agent, we found that the JDK dynamic agent to help us talk about proxy class and delegate class binding relationship delay, when and when, so our business class has not only been enhanced, but also simplifies the code.

Of course, the JDK dynamic agent also has a flaw, do not know that you have found no, here each delegate class must have the interface, that is, the JDK dynamic proxy depends on the interface implementation, if I do not have the interface of the class want to be proxy what to do?

If some classes do not implement an interface, you cannot use the JDK proxy, which will use the Cglib dynamic proxy. Take a look at the next blog post.



Talking about the knowledge of Java proxy pattern two

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.