High-tech: Agent

Source: Internet
Author: User

-------Android Training, Java training, look forward to communicating with you! ----------


I. Overview
1. Definition

What is an agent? The agent is to provide a proxy to the target object to control access to the object, like these terms what the most annoying, although the expression is correct, but it is difficult to remember, or in plain words to summarize,

I think the proxy is accessing another class through one class.

The proxy class has the same interface as the target class (the delegate Class), which provides additional processing or different operations for the target class, such as exception handling, run time, log, and object management.

The object of the proxy class does not actually implement the service, but instead provides the service by invoking the relevant method of the target class/Delegate class object.

Do not think of the design mode of the proxy mode, yes, today to talk about the agent in fact and design mode of the proxy model is essentially the same.

2. What are the advantages of using an agent?

The main purpose of using the agent is to control the target class precisely.

When we call a method of a class, not only to the result after the method call, but also to call the method before and after adding a program of its own definition and execution, then the use of Agent technology is very convenient.


3, Agent structure diagram



4. Static Agent and dynamic agent

Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.

Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.

That is, the static proxy class runs before the dynamic proxy class runs.

If we use static proxy, we need to increase the proxy function for the classes of various interfaces in the system, which will require too many proxy classes, all using static proxy mode, it will be a very troublesome thing.

Therefore, we mainly adopt the dynamic proxy approach. Some frameworks are also implemented through dynamic proxies.


Ii. creating dynamic classes and viewing methods


1, dynamic proxy class creation code (here, for example, the collection Class)

Returns a class object for the proxy class, a parameter (class loader, implemented interface) class Clazzproxy = Proxy.getproxyclass (Collection.class.getClassLoader (), Collection.class);
2, get the construction method of dynamic proxy class

private static void Creatconstructor (Class clazzproxy) {constructor[] cons = Clazzproxy.getconstructors (); for ( Constructor constructor:cons) {String name = Constructor.getname (); StringBuilder sb = new StringBuilder (name); Sb.append (' ('); class[] cls = Constructor.getparametertypes (); for (Class class1:cls) {sb.append (Class1.getname ()). Append (', ');} Sb.append (') '); SYSTEM.OUT.PRINTLN (SB + "...");}

3, get the general method of dynamic proxy class

private static void Creatmethod (Class clazzproxy) {method[] methods = Clazzproxy.getmethods (); for (Method method:methods ) {String name = Method.getname (); StringBuilder sb = new StringBuilder (name); Sb.append (' ('); class[] cls = Method.getparametertypes (); for (Class class1:cls) {sb.append (Class1.getname ()). Append (', ');} Sb.append (') '); SYSTEM.OUT.PRINTLN (SB + "...");}

Iii. creating an instance object of a dynamic proxy class and calling its methods

1, the same as the internal class mode implementation

private static void InstanceObj1 (Class clazzproxy) throws Exception {//According to the Creatconstructor () method Clazzproxy No Construction method// Invocationhandler: Is the interface that is implemented by the calling handler for the proxy instance. Contains only one method invokeconstructor con = clazzproxy.getconstructor (invocationhandler.class);//Implement the method class Myinvocation by the inner class form Implements Invocationhandler {@Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable { Here write the specific operation of the called Target (destination class) return null;}} Collection proxy1 = (Collection) con.newinstance (New Myinvocation ()); System.out.println (proxy1);}


2, implemented by anonymous inner class method
/** * Get a dynamic proxy class, overwrite, by anonymous inner class *  */private static void InstanceObj2 (class Clazzproxy) throws Exception {//according to Creatconstru The ctor () method shows that Clazzproxy has no construction method constructor con = clazzproxy.getconstructor (invocationhandler.class); Object proxy1 = Con.newinstance (New Invocationhandler () {@Overridepublic object Invoke (Object proxy, Method method, object[] args) Throws Throwable {return null;}}); System.out.println (proxy1);}

3, through the Proxy.newproxyinstance () method

/** * Gets a dynamic proxy class, via the Proxy.newproxyinstance () method */private static void InstanceObj3 () {Collection proxy1 = (Collection) proxy . Newproxyinstance (Collection.class.getClassLoader (),//first parameter, define class loader for proxy class new class[] {collection.class},  // The second parameter, the proxy class to implement the interface list new Invocationhandler () {  ////third parameter, assigns the call handler of the method call @overridepublic object Invoke (object proxy, Method method,object[] args) throws Throwable {ArrayList target = new ArrayList (); return Method.invoke (target, args);});}


Four, the realization principle of dynamic proxy class




This picture is still very image, in the circle of the part of the add their own code, the client by calling the dynamic proxy class of a method, through the Invocationhandler Interface Invoke () method call Target (target Class) the same method.



Five, write a generic dynamic agent.


1, first define an interface

Package Cn.jinfulin.day3.proxy;import Java.lang.reflect.method;public interface Iadvice {void Beformethod (Method method); void Aftermethod (method);}
2. Implement this interface

Package Cn.jinfulin.day3.proxy;import Java.lang.reflect.method;public class Myadvice implements Iadvice {long beginTime; @Overridepublic void Beformethod (method) {beginTime = System.currenttimemillis (); System.out.println (Method.getname () + "Welcome to learn dynamic agent,");} @Overridepublic void Aftermethod (method) {Long endTime = System.currenttimemillis (); System.out.println (Method.getname () + "I have learned the agent, time" + (Endtime-begintime));}}

3, write dynamic proxy class method

/** * Finally rewritten proxy class */private static object Finnalmethod (Final object target,final Iadvice advice) {Object proxy1 =  Proxy. Newproxyinstance (//Create a new instance of the dynamic proxy class Target.getclass (). getClassLoader (),//The first parameter, which defines the class loader target.getclass () of the proxy class. Getinterfaces (),///second argument, the proxy class to implement the interface list for new Invocationhandler () {  ////third parameter, the call handler that assigns the method call @overridepublic Object Invoke (Object Proxy, method method,object[] args) throws Throwable {Advice.beformethod (method);//Add a method to the target class object retval = Method.invoke (target, args); Advice.aftermethod (method);//Add a method of the target class return Retval;//return Method.invoke ( Target, args);}); return proxy1;}

4, the client calls

ArrayList target = new ArrayList (); Collection proxy = (Collection) finnalmethod (target,new myadvice ());p Roxy.add ("Jinfoling");//Using a method, It is equivalent to calling the Invoke Method Proxy.clear (); \ \ Second Call SYSTEM.OUT.PRINTLN (Proxy.size ()); \ \ Third Call


5, results




Vi.. Last


Agent finally finished, later to rely on Java to eat, Java Basic Learning is still very necessary, the future development is in these knowledge based on the use of frameworks and APIs to do development. After all, original aim, master the basic principles to better use of tools.



High-tech: Agent

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.