Java Dynamic Proxy mode

Source: Internet
Author: User

A detailed description of the Java dynamic Agent mechanism

The principle of spring's core AOP is the dynamic proxy mechanism of java.

In the dynamic agent mechanism of Java, there are two important classes or interfaces:

1.InvocationHandler (Interface):

Each dynamic proxy class must implement the Invocatonhandler interface, and each instance of the proxy class is associated to a handler, and when we invoke a method through the proxy object, the call to this method is forwarded to the

Invocatonhandler the Invoke method of this interface to make the call.

 Public Object Invoke (Object Proxy,method method,object[] args)throws  throwable  {  }

Proxy: On behalf of the real object that we represent;

Method: Only takes the method object that we want to invoke the real object of a certain way;

Args: Refers to a parameter that is accepted when a method of a real object is called.

2.Proxy (Class)

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

1 public static Object newproxyinstance (ClassLoader loader,class<?>[] Interface, Invocationhandler h)throws illegalargumentexception

Loader: A Classloder object that defines the ClassLoader object to load the generated proxy object;

interface: An array of interface objects that represent the set of excuses that I will give to my object that needs to be represented, and if I provide a set of excuses for him, then this proxy object declares that the interface is implemented (polymorphic), So I can invoke the methods in this set of interfaces;

h: A Invocationhandler object that represents which Invocationhandler object the proxy object will be associated with when it invokes the method.

  

"Code Listing--1" abstract object role:

1  PackageCom.huawei.subject;2 /**3 * Abstract Object Role4  * @authorAdministrator5  *6  */7  Public InterfaceSubject8 {9     voidrent ();Ten     voidhello (); One}

"Code Listing--2" real object role

1  PackageCom.huawei.subject.Impl;2 3 ImportCom.huawei.subject.Subject;4 /**5 * Real Object role6  * @authorAdministrator7  *8  */9  Public classRealsubjectImplementsSubjectTen { One  A @Override -      Public voidrent () -     { theSYSTEM.OUT.PRINTLN ("I want to rent my building"); -     } -  - @Override +      Public voidHello () -     { +System.out.println ("Hello tenants"); A     } at  -}

"Code Listing--3" proxy class

1  PackageCom.huawei.proxy;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Method;5 6 /**7 * Dynamic Agent role8  * @authorAdministrator9  *Ten  */ One  Public classDynamicproxyImplementsInvocationhandler A { -     //This is the real object we're going to be acting for. -     PrivateObject subject; the     //constructs a method, assigns the initial value to the real object which we want to proxy -      Publicdynamicproxy (Object obj) -     { -          This. Subject =obj; +     } -      +  A @Override at      Publicobject Invoke (Object object, method method, object[] args) -             throwsThrowable -     { -         //you can do some of your own work before acting on the real object -System.out.println ("Mrthod:" +method); -         //when a contemporary object invokes a method of a real object, it automatically jumps to the Invoke method of the proxy object's handler object to invoke in Method.invoke (subject, args); -          to         //you can perform some of your own operations after you have proxied the real object +          -         return NULL; the     } *  $}

"Client"--test class

1  PackageCom.huawei;2 3 ImportJava.lang.reflect.InvocationHandler;4 ImportJava.lang.reflect.Proxy;5 6 ImportCom.huawei.proxy.DynamicProxy;7 ImportCom.huawei.subject.Subject;8 ImportCom.huawei.subject.Impl.RealSubject;9 Ten  Public classMain { One  A      Public Static voidMain (string[] args) -     { -         //the real object we're going to be acting for theSubject 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); -         /** + * Use Proxy's Newinstance method to create our proxy object - * The first parameter Handler.getclass (). getClassLoader (), we use this here + * Handler The ClassLoader object of this class to load our proxy object; A * The second parameter Realsubject.getclass (). GetInterface (), the interface we provide here for the proxy object at * is the actual object implementation of the interface, that I want to proxy is the real object, so I can call this set of interfaces in the method; - * The third parameter, handler, says this proxy object is associated to the object above the Invocationhandler. -          */ -          -Subject Subject =(Subject) proxy.newproxyinstance (Handler.getclass (). getClassLoader (), - Realsubject.getclass (). Getinterfaces (), in handler); -          to System.out.println (Subject.getclass (). GetName ()); +          - subject.rent (); the Subject.hello (); *  $     }Panax Notoginseng  -}

"Run Results"

com.sun.proxy. $Proxy 0Mrthod:  Public Abstract void com.huawei.subject.Subject.rent () I want to rent my Buildingmrthod:  Public Abstract void Com.huawei.subject.Subject.hello () tenant Hello

The proxy object created through proxy.newinstance is an object that is dynamically generated when the JVM runs, not our Invocationhandler type, nor the type of interface we define. Instead, an object that is dynamically generated at run time,

And obviously the way is this form, with $ start, proxy for the first, the last number represents the object's label.

Subject.rent ();
Subject.hello ();

Here is the method through the proxy object to invoke the implementation of that interface, this time the program will jump to the proxy object associated with the handler invoke method to execute, and we

This handler object also accepts a parameter of type Realsubject, which means that the real object is the one I want to proxy, so the Invoke method in handler is called to execute.

The result shows that when we invoke the method through the proxy object, it is actually called by the Invoke method of the handler object that the delegate has associated with, not by its own real invocation, but by the proxy method.

Java Dynamic Proxy mode

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.