Understanding of dynamic Agent in Java

Source: Internet
Author: User

Agents can be divided into two categories: static agents and dynamic agents

1. Static Proxy:

/*define a business interface*/ Public InterfaceCount {//View account Methods     Public voidQuerycount (); //Modify Account Method     Public voidUpdatecount (); }/*define a delegate class that implements the business interface*/ Public classCountimplImplementsCount {@Override Public voidQuerycount () {System.out.println ("View Account Method ..."); } @Override Public voidUpdatecount () {System.out.println ("Modify Account Method ..."); }  }  

First, define a business interface, and then define a delegate class, and all we have to do is static proxy delegate classes:

/*defines a static proxy class that proxies the delegate class Countiml*/ Public classCountproxyImplementsCount {PrivateCountimpl Countimpl; /*** Override default constructor * *@paramCountimpl*/       Publiccountproxy (Countimpl countimpl) { This. Countimpl =Countimpl; } @Override Public voidQuerycount () {System.out.println ("Before transaction processing"); //the method of invoking the delegate class; Countimpl.querycount (); System.out.println ("After transaction processing"); } @Override Public voidUpdatecount () {System.out.println ("Before transaction processing"); //the method of invoking the delegate class; Countimpl.updatecount (); System.out.println ("After transaction processing"); }  }  

As shown in the code: Define a proxy class to handle the transaction of the delegate class

 Public class Testcount {      publicstaticvoid  main (string[] args) {          new  Countimpl ();           New Countproxy (Countimpl);          Countproxy.updatecount ();          Countproxy.querycount ();        }  

However, we also found that if the agent processing logic is different, and to redefine a proxy class, this is unreasonable, so the dynamic agent came into being

2. Dynamic Agent:

The biggest benefit of dynamic proxies compared to ordinary proxies is that all the methods declared in the interface are transferred to a centralized approach (invoke), so that when the number of interface methods is greater, we can do it flexibly without needing to relay every method like a static proxy.
The dynamic proxy class can only proxy interfaces, and the proxy class needs to implement the Invocationhandler class to implement the Invoke method. The Invoke method is called when calling all methods of the Proxied interface, and the value returned by the Invoke method is an implementation class of the Proxy interface

Dynamic proxy classes will implement the same interface Invocationhandler

 Public Interface Invocationhandler {     publicthrows

Parameter Description: Object proxy, refers to the objects being proxied; Method refers to the methods of the object being proxied; object[] args refers to the method parameters

Proxy class:

An action class that specifically completes an agent, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following methods of action:

 Public Static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h)throws ////////

The following is a very classic example of dynamic proxy:

The first step is to define a business interface:

     Public Interface Targetinterface {          publicint targetmethoda (int number );            Public int targetmethodb (int number );      }  

The second step is to define a business class that implements the business interface-that is, the corresponding delegate class:

     Public classConcreteclassImplementstargetinterface{ Public intTargetmethoda (intNumber ) {System.out.println ("Start calling methods of target class Targetmethoda ..."); System.out.println ("Action-Print Numbers:" +Number ); System.out.println ("End call to target class method Targetmethoda ..."); returnNumber ; }                     Public intTargetmethodb (intNumber ) {System.out.println ("Start calling methods of target class Targetmethodb ..."); System.out.println ("Action-Print Numbers:" +Number ); System.out.println ("End call to target class method Targetmethodb ..."); returnNumber ; }            }  

The third step is to define the proxy class:

     Public classProxyhandlerImplementsinvocationhandler{PrivateObject Concreteclass;  PublicProxyhandler (Object concreteclass) { This. concreteclass=Concreteclass; }                 PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Proxy:" +Proxy.getclass (). GetName ()); System.out.println ("Method:" +method.getname ()); System.out.println ("Args:" +args[0].getclass (). GetName ()); System.out.println ("Before Invoke Method ..."); Object Object=method.invoke (Concreteclass, args);//Common Java Reflection code that executes a method of a class by reflectionSystem.out.println ("After Invoke method ..."); returnobject; }            }  

The proxy class implements the Invocationhandler interface in the Java reflection Package, where the proxy instance invokes the method and assigns the method invocation to the Invoke method of its agent handler program. The Invoke method internally implements the preprocessing, the invocation of the delegate class method, and the post-processing logic.

Fourth Step, test procedure

     Public classDynamicproxyexample { Public Static voidMain (string[] args) {Concreteclass C=NewConcreteclass ();//Meta-Object (Proxied object)Invocationhandler ih=NewProxyhandler (c);//the invocation handler for the proxy instance. //Create a proxy class that implements the business interface for accessing the business class (see proxy mode). //returns a proxy class instance of a specified interface that can assign a method call to a specified invocation handler, such as Proxyhandler. Targetinterface targetinterface=(Targetinterface) proxy.newproxyinstance (C.getclass (). getClassLoader (), C.getclass (). Getinterfaces (), IH); //Call the proxy class method, Java executes the Invocationhandler interface method.              intI=targetinterface.targetmethoda (5);               System.out.println (i);               System.out.println (); intJ=targetinterface.targetmethodb (15);          System.out.println (j); }      }  

A proxy class instance is created using the Proxy.newproxyinstance method in the Java reflection mechanism, which needs to specify the class loader for that instance, the interface to be implemented (that is, the target interface), and the processor that handles the proxy instance interface invocation.

Benefits of using the Java Dynamic Agent:

1, reduce the workload of programming: if you need to implement a variety of agent processing logic, as long as write multiple agent processor on it, no need to write a proxy class each way.

2, System expansion and maintenance enhancements, the program is also more convenient to modify (generally as long as the agent processor class on the line).

Understanding of dynamic Agent 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.