A detailed explanation of dynamic agent mechanism in Java

Source: Internet
Author: User

When we learn spring, we know that spring has two main ideas, one is the IOC, the other is AOP, and for IOC, dependency injection doesn't have to be said, and for spring's core AOP, we not only need to know how to satisfy our function through AOP, What we need to learn is how the underlying is a principle, and the principle of AOP is the dynamic agent mechanism of Java, so this essay is a review of the dynamic mechanism of java.

In the dynamic agent mechanism of Java, there are two important classes or interfaces, one is Invocationhandler (Interface), the other is proxy (class), and this class and interface is necessary to implement our dynamic proxy. First, let's take a look at how the Java API Help document describes these two classes:

Invocationhandler:

Invocationhandler is the interface implemented by the invocation handler of a proxy instance. Each proxy instance have an associated invocation handler. When a method was invoked on a proxy instance, the method invocation was encoded and dispatched to the Invoke method of its Invocation handler.

Each dynamic proxy class must implement the Invocationhandler interface, and each instance of the proxy class is associated with a handler, and when we call a method through the proxy object, The invocation of this method is forwarded to the Invoke method of this interface by Invocationhandler. Let's take a look at the only way to invocationhandler this interface. The Invoke method:

throws Throwable

We see that this method takes three parameters altogether, so what do these three parameters represent?

throws Throwable
Proxy:referring to the real object that we are acting for.
Method:refers to the method object that we are going to call the real object
args:refers to parameters that are accepted when a method of a real object is called

If not very clear, wait for an example to explain these parameters in more depth.

Next we look at the proxy class:

Proxy provides static methods for creating dynamic proxy classes and instances, and it's also the superclass of all Dynam IC proxy classes created by those methods.

The role of the proxy class is to dynamically create a class of proxy objects, which provides a number of methods, but the most we use is newproxyinstance this method:

 Public Static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) Throwsillegalargumentexception
Returns an instance of a proxy class for the specified interfaces, dispatches method invocations to the specified INVO cation handler.

The function of this method is to get a dynamic proxy object, which receives three parameters, and we take a look at what these three parameters mean:

 Public Static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) Throwsillegalargumentexception
Loader:a ClassLoader object that defines which ClassLoader object to load for the generated proxy object
Interfaces:an array of interface objects, which means that I'm going to provide a set of interfaces to the object I need to proxy, and if I provide a set of interfaces to it, then the proxy object declares that the interface is implemented (polymorphic) so that I can invoke the methods in this set of interfaces.
h:a Invocationhandler object that represents the Invocationhandler object to which the dynamic proxy object is associated when it invokes the method.

Well, after the introduction of these two interfaces (classes), let's look at an example of what our dynamic proxy pattern looks like:

First we define an interface of type subject and declare two methods for it:

 Public Interface
Public void   rent (); publicvoid Hello (String str);
}

Next, define a class to implement this interface, this class is our real object, Realsubject class:

 Public class Implements subject{     publicvoid  rent () {         System.out.println ("I-Want to rent my house" );     }     @Override     publicvoid  hello (String str) {         System.out.println (" Hello: "+ str");}     }

Next, we are going to define a dynamic proxy class, the previous one, each dynamic proxy class must implement Invocationhandler this interface, so we this dynamic proxy class is no exception:

 Public classDynamicproxyImplementsinvocationhandler{//This is the real object we're going to be acting for.    PrivateObject subject; //constructs a method, assigns the initial value to the real object which we want to proxy     PublicDynamicproxy (Object subject) { This. Subject =subject;} @Override PublicObject Invoke (Object object, method method, object[] args)throwsThrowable {//we can add some of our own actions before acting on the real object.System.out.println ("Before Rent house"); System.out.println ("Method:" +method); //when a contemporary object invokes a method of a real object, it automatically jumps to the Invoke method of the handler object associated with the proxy object .Method.invoke (subject, args); //We can also add some of our own actions after acting on the real object.System.out.println ("After Rent house"); return NULL; }}

Finally, take a look at our client class:

 Public classclient{ Public Static voidMain (string[] args) {//the real object we're going to be acting forSubject Realsubject =NewRealsubject (); //we're going to proxy which real object, we'll pass the object in, and finally we'll call its method through the real object .Invocationhandler handler =NewDynamicproxy (Realsubject); /** Using Proxy's Newproxyinstance method to create our proxy object, let's take a look at its three parameters * the first parameter Handler.getclass (). getClassLoader (), we use Handl here Er this class of ClassLoader object to load our proxy object * The second parameter Realsubject.getclass (). Getinterfaces (), the interface we provide here for the proxy object is the interface that the real object implements, I'm going to represent the real object, so I can invoke the method in this set of interfaces * The third parameter handler, where we associate this surrogate object to the Invocationhandler above*/Subject Subject=(Subject) proxy.newproxyinstance (Handler.getclass (). getClassLoader (), Realsubject. GetClass (). Getinterfaces ()      , handler);      System.out.println (Subject.getclass (). GetName ());      Subject.rent (); Subject.hello ("World"); }}

Let's take a look at the console output:

$Proxy 0before rent Housemethod:  Public Abstract void com.xiaoluo.dynamicproxy.Subject.rent () I want to rent my houseafter rent housebefore rent housemethod:  Public Abstract void Com.xiaoluo.dynamicproxy.Subject.hello (java.lang.String) hello:worldafter rent House

Let's start by looking at $Proxy 0 this thing we see, this thing is made by System.out.println (Subject.getclass (). GetName ()); This statement is printed, so why is the class name of the proxy object that we return?

Subject Subject = (Subject) proxy.newproxyinstance (Handler.getclass (). getClassLoader (), Realsubject. GetClass (). Getinterfaces (), handler);

Maybe I thought the returned proxy object would be an object of type subject or a Invocationhandler object, but the result is not, first we explain why we can convert it to an object of type subject? the reason is that in newproxyinstance the second parameter of this method, we give this proxy object to provide a set of what interface, then I this proxy object will implement this set of interfaces, this time we can of course, this proxy object coercion type into any of the set of interfaces , because the interface here is the subject type, so it can be converted to the subject type.

at the same time we must remember that the proxy object created through Proxy.newproxyinstance is an object that is dynamically generated when the JVM is running, it is not our invocationhandler type, nor is it the type of the set of interfaces we define. Instead, the run is a dynamically generated object, and the naming method is in this form, starting with $, proxy is medium, and the last number represents the label of the object .

Then we'll take a look at these two sentences.

subject.rent (); Subject.hello ("World");

Here is a proxy object to invoke the implementation of the interface method, this time the program will jump to the proxy object associated with the handler invoke method to execute, and our handler object has accepted a realsubject type of parameters, This is the real object that I want to proxy, so I'm going to call the Invoke method in handler to do it:

 PublicObject Invoke (Object object, method method, object[] args)throwsThrowable {//we can add some of our own actions before acting on the real object.System.out.println ("Before Rent house"); System.out.println ("Method:" +method); //when a contemporary object invokes a method of a real object, it automatically jumps to the Invoke method of the handler object associated with the proxy object .Method.invoke (subject, args); //We can also add some of our own actions after acting on the real object.System.out.println ("After Rent house"); return NULL; }

We see that we can add some of our own operations before and after the method that actually invokes the real object through the proxy object, and we see that we have a method object like this:

 Public Abstract void com.xiaoluo.dynamicproxy.Subject.rent ()  Public Abstract void Com.xiaoluo.dynamicproxy.Subject.hello (java.lang.String)

Exactly the two methods in our subject interface, which proves that when I invoke a method through a proxy object, it is actually called by the Invoke method of the handler object to which the delegate is associated, not by itself, but by proxy.

This is our Java Dynamic Agent mechanism.

This essay explains in detail the dynamic agent mechanism in Java, the knowledge point is very important, including our spring AOP is implemented through the mechanism of dynamic proxy, so we must understand the mechanism of dynamic agent.

A detailed explanation of dynamic agent mechanism in Java

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.