Welcome to the Csdn-markdown Editor

Source: Internet
Author: User

Java Dynamic Agent

A proxy is a class that has the same interface as the proxy (the object being proxied) , and the client must interact with the target class that is being proxied through the proxy, and the agent typically does some special processing during the interaction (before and after the interaction).

Proxy mode is a very common mode, in our lives everywhere, for example, we buy train tickets do not have to go to the railway station to buy, you can go to some of the train tickets to buy. Letters may not be sent by themselves, but they can be entrusted to the Post office and sent to the destination by the post office.

The above can also be called static Proxy, is to distinguish the proxy mode in Java, another implementation-dynamic agent. Dynamic agent is widely used, and the dynamic agent mechanism is used in the Struts2 interceptor.

1 static proxies

In some cases, we do not want or can not directly access object A, but by accessing a mediation object B, B to access a to achieve the purpose, this way we are called proxies.
Here object A belongs to the class that we call the delegate class, also known as the proxy class, and object B belongs to the class called the proxy class.
The advantages of the agent are:

    • To hide the implementation of a delegate class
    • Decoupling, do some extra processing without changing the delegate class code, such as adding initial judgment and other public operations
    • Depending on whether the agent class already exists before the program runs, you can divide the agent into static agents and dynamic proxies.

      Proxy classes that exist before a program is run are called static proxies.
      As you can see from the above explanation, the way that the developer writes or the compiler generates the proxy class belongs to the static proxy, and the following is a simple static proxy instance:

Class ClassA { Public void operateMethod1() {    }; Public void operateMethod2() {    }; Public void operateMethod3() {    };} Class ClassB {PrivateClassA A; Public ClassB(ClassA a) { This. A = A; } Public void operateMethod1() {a.operatemethod1 (); }; Public void operateMethod2() {a.operatemethod2 (); };//Not Export operateMethod3 ()}}

The above ClassA is a delegate class, CLASSB is a proxy class, CLASSB functions are called directly classa the corresponding function, and the class's operateMethod3 () function is hidden.

Proxy classes and delegate classes in static proxies also often inherit the same parent class or implement the same interface.

2 Dynamic Agents

The proxy class does not exist before the program runs, and the proxy mode that is dynamically generated by the program is called a dynamic proxy.

Java provides a way for dynamic proxies to dynamically generate proxy classes at run time. One of the great benefits of this proxy approach is that it makes it easy to do uniform or special handling of the functions of the proxy class, such as recording all function execution times, adding validation judgments before all functions are executed, and special operations on a particular function rather than modifying each function as a static proxy.

Static proxy is relatively simple, this article has been briefly described above, the following focus on dynamic agents.

2.1 Dynamic Proxy instances implementing dynamic proxies includes three steps:
    1. New delegate class;
    2. Implementation of the Invocationhandler interface, which is responsible for connecting the proxy class and the intermediate class of the delegate class must implement the interface;
    3. Creates a new proxy class object from the proxy class.
2.1 New Delegate Class
interface  operate  { public  void  operateMethod1 (); public     void  operateMethod2 (); public  void  operateMethod3 ();} class  operateimpl  Span class= "hljs-inheritance" >implements    Operate  { @Override public  void  o        PerateMethod1 () {System.out.println ( "Invoke operateMethod1" );    Sleep (110 ); }

Operate is an interface that has certain functions, and we want to count the execution time of these functions.
Operateimpl is a delegate class that implements the operate interface. Each function simply outputs a string and waits for some time.
The dynamic proxy requires that the delegate class must implement an interface, such as the delegate class Operateimpl implemented operate.

2.2 Implementing the Invocationhandler interface
 class Timinginvocationhandler implements Invocationhandler {    PrivateObject Target; PublicTiminginvocationhandler () {} PublicTiminginvocationhandler (Object target) { This. target = target; } @Override PublicObject Invoke (Object proxy, Method method, object[] args) throws Throwable {LongStart = System.currenttimemillis ();        Object obj = Method.invoke (target, args); System.out.println (Method.getname () +"Cost time is :"+ (System.currenttimemillis ()-start));returnObj }}

The target property represents the delegate class object.

Invocationhandler is the interface that the intermediate classes that are responsible for connecting proxy classes and delegate classes must implement. Only one of them

public object invoke (object proxy, Method method, object[] args)

Functions need to be implemented, parameters:
Proxy represents the agent class object generated by Proxy.newproxyinstance () below 2.3.
Method represents the function that the proxy object is called.
Args represents the parameters of the function that the proxy object is called.

Each function that invokes the proxy object actually eventually calls the Invocationhandler invoke function. Here we add the start-end timing in the invoke implementation, which also invokes the corresponding function of the target of the delegate class object, thus completing the statistical execution time requirement.
In the Invoke function, we can also make some judgments about the method, so that some functions are handled specially.

2.3. Generating proxy objects through proxy class static functions
class Main{public static void main(String[] args){//Create Proxyinstance                 TiminginvocationhandlerTiminginvocationhandler = newTiminginvocationhandler(new Operateimpl());Operateoperate =(Operate)(Proxy. ) Newproxyinstance(Operate.  Class. getClassLoader (), newClass[] {Operate.class}, Timinginvocationhandler)); Call method of ProxyinstanceOperate.operatemethod1();System. out.println(); Operate.operatemethod2();System. out.println(); Operate.operatemethod3(); } }

Here we first create the Timinginvocationhandler object with the delegate class object new Operateimpl () as the Timinginvocationhandler constructor parameter;

Then through Proxy.newproxyinstance (...) function creates a new proxy object, and the actual proxy class is generated dynamically at this time. The function we call the proxy object calls to the Timinginvocationhandler invoke function (not a bit like a static proxy), while the Invoke function implementation calls the delegate class object new Operateimpl () corresponding method ( is not a bit like a static proxy).

publicstaticObjectClass<?>[] interfaces, InvocationHandler h)

Loader represents the class loader
Interfaces represents the interface of the delegate class, which needs to be implemented when generating the proxy class
H is the Invocationhandler implementation class object, which is responsible for connecting the intermediate classes of the proxy class and the delegate class

We can understand that, as on the dynamic proxy implementation is actually a two-tier static proxy, the developer provides the delegate class B, the program dynamically generated proxy class A. The developer also needs to provide a subclass C that implements the Invocationhandler, a subclass C connection proxy Class A and a delegate class B, which is the delegate class of the proxy class A, and the proxy class of the delegate Class B. The user calls the object of the proxy class A directly, a forwards the call to the delegate Class C, and the delegate Class C forwards the call to its delegate class B.

Welcome to the Csdn-markdown Editor

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.