Java Dynamic proxy (example)

Source: Internet
Author: User

To implement dynamic proxy through JDK, classes with proxy requirements (called implementation classes) must implement interfaces. The dynamic proxy can segment the logic and implement the logic through the proxy generation. Other operations can be performed during this period. JDK's dynamic proxy mainly involves two classes in the Java. Lang. Reflect package: proxy and invocationhandler. Invocationhandler is an interface that defines the cross-cutting logic by implementing this interface and calls the target class through the reflection mechanism.CodeTo dynamically combine the cross-cutting logic and business logic. I have been confused about the dynamics, but I cannot tell them clearly. Today I have a new understanding. The following is a simple example:

First, describe the transaction logic: A person (people object) goes to a foreign country (Japan, UK) through the transport (Transportation processing class)

1. Use the two tasks "going to the UK and Japan" as two interfaces, which are implemented by humans.

 Package  Com. impetention. lei;  Public   Interface  Japan {  Public   Void Gojapan ();} -------------------------------------------- Package  Com. impetention. lei;  Public   Interface  England {  Public   Void  Goengland ();} ------------------------------------------------- Package  Com. impetention. lei;  //  Implementation class  Public  Class People Implements  England, Japan {@ override  Public   Void  Goengland (){  //  Todo auto-generated method stub System. Out. println ("I am in England! " ) ;}@ Override  Public   Void  Gojapan (){  // Todo auto-generated method stub System. Out. println ("I am in Japan! " );}} 

2. Let's introduce it now.InvocationhandlerIt is the processing of proxy calls.ProgramImplemented interface. Each proxy class has an associated call handler. when instantiating the proxy class, it is added to an invocationhandler type processing class (the topic that completes the transaction logic ).

For example:

 Package  Com. Invocation;  Import  Java. Lang. Reflect. invocationhandler;  Import  Java. Lang. Reflect. method;  Import  Com. impetention. Lei. People; //  People go abroad by means of transportation (Agency)  Public   Class Transportation Implements  Invocationhandler {  //  A person named Zhang      Private Object Zhang = Null  ;  Public  Transportation (Object Zhang ){  This . Zhang =Zhang ;}@ override  Public  Object invoke (Object proxy,Method method, object [] ARGs ){  //  Todo auto-generated method stub System. Out. println ("You can execute some other methods ....." );  //  Record execution results Object result = Null  ; Zhang = New  People (); //  Execute the method on the Zhang object and return the result          Try  {Result = Method. Invoke (Zhang, argS );}  Catch  (Exception e ){  //  Todo auto-generated Catch Block  E. printstacktrace ();} system. Out. println ( "---------------------" );  Return  Result ;}} 

Pay attention to the red proxy, which is a proxy instance. It is necessary to explain invoke (Object proxy, method, object [] ARGs,When the dynamic proxy class proxy0 calls the goengand () method, it will call its own goengand () method,In its own goengand () method, the invoke () method of the invocationhandler object bound to it is called,That is, transportation.Invoke (Object proxy, method M, object [] ARGs) proxy is actually a dynamic proxy class proxy, If you convert it to England then call its goengland () method, it will trigger the goengland () method of the proxy class, and the proxy class will call the invocationhandler (Transportation) invoke () method, this will lead to an endless loop.

 

3. Proxy implementation:

 Package  Com. Main; Import  Java. Lang. Reflect. proxy;  Import  Com. impetention. Lei. engand;  Import  Com. impetention. Lei. Japan;  Import  Com. impetention. Lei. People;  Import  Com. Invocation. transportation;  Public   Class  Peopletest {  Public   Static  Void  Main (string [] ARGs ){  //  We are going to use dynamic agents. A person named Li has arrived in the UK by means of transportation. England li = New  People ();  //  Instantiate a transportation object Transportation T1 = New  Transportation (LI );  // Use Li. getclass (). getclassloader () to implement the class loader and Li. getclass (). getinterfaces () to implement all interfaces implemented by the class as parameters. 
// Proxy. getproxyclass (classloader loader, class <?>... Interfaces) method returns the java. Lang. Class Object of the proxy class to obtain a proxy class,
//You must give it an invocationhandler parameter, that is, what we implement is used in the proxy classClass Transpotation that performs additional work before and after method execution. Set proxy classConvert to England type
England proxy = (England) proxy. newproxyinstance (Li. getclass (). getclassloader (), Li. getclass (). getinterfaces (), T1); proxy. goengland ();  //  We are going to use dynamic agents. A person named Li has arrived in the UK by means of transportation. Japan Lei = New  People ();  // Instantiate a transportation object Transportation t2 = New  Transportation (LEI );  //  Use Li. getclass (). getclassloader () and Li. getclass (). getinterfaces () to obtain  //  (Java. Lang. Class) proxy class, instantiate it with TT as the parameter, and convert it to the people type Japan proxy1 =(Japan) proxy. newproxyinstance (Li. getclass (). getclassloader (), Li. getclass (). getinterfaces (), T2); proxy1.gojapan ();}}
Summary:The process is like this. People does not execute the goengand () method directly. Instead, they execute its own goengand () through the proxy class proxy, which triggers transportation to call invoke () and then
 
Method. Invoke (Zhang, argS );Zhang will call its method, goengand (), and return the result.
Related Article

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.