Understand java Dynamic proxy and java Dynamic proxy

Source: Internet
Author: User

Understand java Dynamic proxy and java Dynamic proxy

Java Dynamic proxy is an advanced feature of java. During Normal project development, it may be difficult to encounter dynamic proxy cases. However, dynamic proxy plays an irreplaceable role in many frameworks, such as Spring's AOP. Today we will talk about the implementation principles of java Dynamic proxy.

Jdk's support for dynamic Proxy mainly depends on two classes: Proxy and InvocationHandler. Let's take a look at the class diagram first.

 

The Subject class is a topic class that defines what I want to do. We need the proxy class to implement the RealSubject interface.

  1. InvocationHandler

InvocationHandler interface is an interface provided by jdk, which has only one method

 public Object invoke(Object proxy, Method method, Object[] args)        throws Throwable;

Let's first understand what the InvocationHandler class is. The following are java doc

* <p>Each proxy instance has an associated invocation handler.
* When a method is invoked on a proxy instance, the method
* invocation is encoded and dispatched to the {@code invoke}
* method of its invocation handler.

Each proxy instance is associated with an invocation handler. To be precise, each proxy class holds an InvocationHandler instance and delivers the target function to the InvcationHandler instance for execution. InvocationHandler only has the invoke () method, which is the actually called method. No matter what method the proxy calls, the processor must call the invoke () method. Let's take a look at the parameters of this method.

1. Object proxy. The passed Subject reference is the target object that we want to actually execute.

2. Method method. Method is part of the java reflection API. The method object passed in here is the actually called method.

3. Object [] args. This is an array of parameters passed in when the method is called.

After learning about the invoke () method, you must know how the Subject target method is called? Next we will continue to understand the Proxy class.

2. Proxy

Next we will understand how the Proxy class works with InvocationHandler. The Proxy in java doc is described as follows:

* provides static methods for creating dynamic proxy
* classes and instances, and it is also the superclass of all
* dynamic proxy classes created by those methods.

Proxy provides a static method to create a dynamic Proxy class. The most common method is the following.

 public static Object newProxyInstance(ClassLoader loader,                                          Class<?>[] interfaces,                                          InvocationHandler h)

NewProxyInstance can be used to dynamically create the required proxy object and bind it with the associated InvocationHandler. The parameters are as follows:

1. ClassLoader loader, which loads the class loader of the proxy class.

2. Class <?> [] Interfaces, the proxy class implementation interface. The created proxy class object can only be converted to the subclass of the interfaces.

3. InvocationHandler h, the InvocationHandler associated with the proxy class. All proxy methods are executed through the InvocationHandler's invoke () method.

The newProxyInstance method is a key method for generating proxy classes. A proxy class is generated when the program is running and thus called a dynamic proxy.

3. Case studies

After learning about the two most important classes, we need an instance to help us better understand the running mechanism of dynamic proxy.

First, create a Subject interface and its implementation class.

Step 1. Define Subject

 1 public interface Subject { 2  3     public void say(String str); 4 } 5  6 public class SubjectBean implements Subject { 7  8     @Override 9     public void say(String str) {10         System.out.println(str);11     }12 }

The Subject's say method is the method we need to proxy. Before and after this method, we may wish to do some additional operations. Next we will define our InvocationHandler.

Step 2. Define InvocationHandler

 1 public class MyInvocationHandle implements InvocationHandler { 2  3     Subject subject; 4  5     public MyInvocationHandle(Subject subject) { 6         this.subject = subject; 7     } 8  9     @Override10     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {11         System.out.println("pre");12         method.invoke(subject, args);13         System.out.println("post");14         return null;15     }16 17 }

The constructor is used to pass in the proxy object.

Step 3. Define the proxy generation method implementation

public class Main {    public static Subject getProxy(Subject subject){        return (Subject) Proxy.newProxyInstance(subject.getClass().getClassLoader(),                subject.getClass().getInterfaces(),                new MyInvocationHandle(subject));    }    public static void main(String[] args) {        Subject subject = new SubjectBean();        Subject proxy =  getProxy(subject);        proxy.say("hello");    }}

Run the main function. The output result is:

It can be seen that the true method. invoke (subject, args) of the say () function is completed here. You can add any code snippet before and after execution to enhance the say () method.

4. debug

Let's take a look at the main method debug to see what the proxy class is. For example

  

Com. sun. proxy. $ Proxy () class, which is Proxy. after newProxyInstance is called, an object dynamically generated during jvm Runtime is named in this form, starting with $, proxy as, and the last number indicates the Object Label. The reason why it can be converted to Subject is that we specify its type information in the second parameter passed in.

This article describes the implementation mechanism of java Dynamic proxy. In case of any errors, I hope you can give me more advice.

 

References:

Head First design model

 

 

Author: mayday Taro Source: Birthday.

 

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.