Summary of dynamic agent mechanism in Java

Source: Internet
Author: User
Tags throwable

Since the recent learning of Hadoop in the use of dynamic agent knowledge, before the AOP programming has met, so here specifically summed up.

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:

Object Invoke (Object proxy, Method method, object[] args) throws Throwable

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

Object Invoke (Object proxy, method, object[] args) throws Throwableproxy: Refers to the real object we represent. Method: Refers to the one we want to invoke the real object Method 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:

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)  Throws IllegalArgumentException
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) throws Illegalargumentexceptionloader: A ClassLoader object that defines which ClassLoader object to load the generated proxy object interfaces: An array of interface objects, It 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 it implements the interface (polymorphic) so I can invoke the method in this set of Interfaces H: A Invocationhandler object, Indicates which Invocationhandler object the dynamic proxy object will be associated with when calling the method.

After we have introduced the parameters, we illustrate them with a simple example:

To build the project, look at the code for each file separately:

Subject.java is an interface.

 Package com.darrenchan.entity;  Public Interface Subject {    publicvoid  rent ();      Public void Hello (String str);}

The Realsubject.java implements the subject interface.

 Package com.darrenchan.entity;  Public class Implements Subject {    @Override    publicvoid  rent () {        System.out.println (" I want to rent a house ");    @Override    publicvoid  hello (String str) {        System.out.println (" Hello: "+ str");}    }

We are going to implement the dynamic proxy class, Dynamicproxy.java.

 Packagecom.darrenchan.dynamic;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; 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 proxy, Method method, object[] args)throwsThrowable {//we can add some of our own actions before acting on the real object.System.out.println ("The operation before renting ..."); 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 ("Operation after renting ..."); return NULL; }}

In fact, all methods of invoking the proxy object are converted to invoke the Invoke () method.

Here we are going to generate a dynamic proxy instance, in order to make the code more universal, write a factory class here, Newproxyinstancefactory.java.

 Packagecom.darrenchan.factory;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Proxy;ImportCom.darrenchan.dynamic.DynamicProxy; Public classNewproxyinstancefactory {//generates a dynamic proxy object for the specified subject     Public Staticobject Getproxyinstance (object subject) {//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 (subject); /** Using Proxy's Newproxyinstance method to create our proxy object, let's take a look at its three parameters * the first parameter Subject.getclass (). getClassLoader (), we use SU here Bject This class of ClassLoader object to load our proxy object * The second parameter Subject.getclass (). Getinterfaces (), the interface that we provide for the proxy object is the interface that the real object implements, * represents 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 proxy object to the object above Invocationhandler*/        returnproxy.newproxyinstance (Subject.getclass (). getClassLoader (), Subject.getclass (). Getinterfaces (), handle    R); }}

Finally, let's test it out, Client,java.

 Packagecom.darrenchan.test;ImportCom.darrenchan.entity.RealSubject;ImportCom.darrenchan.entity.Subject;Importcom.darrenchan.factory.NewProxyInstanceFactory; Public classClient { Public Static voidMain (string[] args) {//the real object we're going to be acting forSubject Realsubject =NewRealsubject (); Subject Subject=(Subject) newproxyinstancefactory.getproxyinstance (realsubject);        System.out.println (Subject.getclass (). GetName ());        Subject.rent (); Subject.hello ("World"); }}

Operation Result:

As you can see, each method is inserted before and after the corresponding operation "operation before renting" and "Operation after renting". This is interesting because we do not make calls in a hard-coded way in the program to realize decoupling! This is the core idea of Spring AOP! :

Summary 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.