JAVA Dynamic Agent Learning record

Source: Internet
Author: User

To implement a simple RPC framework with Java, after reading the RPC reference Code, the realization of RPC is mainly used in two aspects of Java Knowledge: network communication and dynamic agent. Therefore, the knowledge of dynamic agents is first mended. ---Take a look at the comments written in the code

Reference: Java proxy mode and dynamic proxy class

A detailed explanation of dynamic agent mechanism in Java

In the dynamic agent, first defines an interface, the method declared in this interface is the real class needs to implement, real class implementation of the method to provide specific operations.

 Public Interface Subject {    publicabstractvoid  request ();}
 Public class extends subject{//Concrete Implementation class     public   realsubject () {            }    publicvoid request () {        System.out.println ("from Real Subject");}    }

With the concrete implementation class, now needs the proxy class, the concrete implementation class in this example is Realsubject.java, it is the proxy class, namely the proxy class agent "The guy" is the concrete implementation class.

The proxy class needs to implement the Invocationhandler interface, why? Let's look at an interface that needs to be used in a Java Dynamic agent: Invocationhandler and a class: Java.lang.reflect.Proxy

There is only one invoke method in the Invocationhandler interface, and the method requires three parameters:

 Public throws throwable{

Proxy: The object of the real class that needs to be proxied
Method: "A way to invoke a real object"
Args: Parameters required to invoke the method

The function of Invocationhandler is to pass the object of the class that needs the proxy as the argument to the constructor, that is, to the proxy class, so that the proxy class knows what the object of the proxy is. Dynamicsubject implements Invocationhandler

    // By passing different types of proxied objects to the construction method, dynamic proxies can be implemented-that is, determining the type    of the object being proxied at run time  Public dynamicsubject (Object obj) {        = obj;    }

At the same time, when making a method call in client code, the Invoke method of the Invocationhandler interface is automatically executed, thus the Method.invoke () in the Invoke method of the Invocationhandler interface Then execute the Real proxy class method.

Method.invoke (sub, args); // invoke the method of the actual method that invokes the object being proxied, that is, realsubject.request ()

Look at the definition of the Invoke () method in Java.lang.reflect.Method in the JDK: invokes the Method underlying method represented by this object on the specified object with the specified argument. The----invokes the specified object sub, specifying the method for the parameter args.

Then look at the role of the proxy class, the proxy class is mainly used to generate a dynamic object in the Clinet code. The object invokes the method to start the dynamic proxy.

/*The first parameter specifies which ClassLoader object to load our proxy object*The second argument for the proxy object is provided by the interface that the real object implements, indicating that I am going to proxy the real object so that I can invoke the methods in this set of interfaces.*The third parameter, handler, associates this proxy object to the above Invocationhandler object, so that when the next actual method call statement is executed, you can
* Knowing which Invocationhandler the delegate is in, the execution will automatically execute the Invocationhandler Invoke method
*/Subject Subject=(Subject) proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), handler); /** When the statement executes, it delegates to the Invoke method in the Invocationhandler class and executes Method.invoke () to make the actual call * Note: Invocationhandler.invoke () has two output statements, and after running the client, it sees its output in the console, indicating that the method was commissioned to execute the*/subject.request ();

The implementation code for the complete dynamic proxy class is as follows:

ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classDynamicsubjectImplementsinvocationhandler{PrivateObject Sub;//An object of Object type, indicating that the object being proxied can be dynamically changed.         PublicDynamicsubject () {}//By passing different types of proxied objects to the construction method, dynamic proxies can be implemented-that is, determining the type of the object being proxied at run time     Publicdynamicsubject (Object obj) {Sub=obj; }         PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable{System.out.println ("Before calling" +method); /** The Object Realsubject sub is obtained in the constructor method.*/Method.invoke (sub, args);//invoke the method of the actual method that invokes the object being proxied, that is, realsubject.request ()System.out.println ("After calling" +method); return NULL; }}

The complete client implementation code is as follows: Client.java in Subject.request (); Represents the start of executing a proxy call. As can be seen from the code, the subject object is dynamically generated by the Proxy.

ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Proxy; Public classClient { Public Static voidMain (string[] args)throwsexception{Realsubject rs=NewRealsubject ();//The class that needs to be proxied, that is, the agent that the client now needs, an object of type Realsubject/*
* Note that the constructor of the proxy class is of type object, stating that it can proxy any type of objects---that the program runs before Dynamicsubject does not know which objects need to be proxied
* Anotherrealsubject Anotherrs = new Anotherrealsubject ();
* Invocationhandler handler = new Dynamicsubject (ANOTHERRS);
*
*/Invocationhandler Handler =NewDynamicsubject (RS);//proxy class, passing in a parameter that requires the proxy class as a constructor of the proxy classClass CLS=Rs.getclass (); /** Class C = proxy.getproxyclass (Cls.getclassloader (), cls.getinterfaces ()); Constructor ct = c.getconstructor (new Class[]{invocationhandler.class}); Subject Subject = (Subject) ct.newinstance (New Object[]{handler}); */ /** The second parameter cls.getinterfaces () ... the CLS is a class object representing the Realsubject type, referencing the getinterfaces () of the class class in the JDK
* Indicates that Newproxyinstance knows which interfaces the dynamically generated proxy object subject need to implement---the interface that needs to be implemented is specified by getinterfaces () .
* While the CLS is a class object representing the Realsubject type, Realsubject implements the Subject interface, so dynamically generated Subject objects can of course
* Coercion type converted.
*/Subject Subject=(Subject) proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), handler); /** When the statement executes, it delegates to the Invoke method in the Invocationhandler class and executes Method.invoke () to make the actual call * Note: Invocationhandler.invoke () has two output statements, and after running the client, it sees its output in the console, indicating that the method was commissioned to execute the*/subject.request (); /** Output: Com.sun.proxy. $Proxy 0 * This indicates that the Subject object type is $Proxy 0 instead of the subject or Invocationhandler type * but is in a 22-line statement, but you can cast it to the subject type * Because Proxy.newproxyinstance generates a dynamic object that is generated when the JVM is running. On the second parameter of Newproxyinstance (), it is provided with a set of interfaces * The proxy object implements this set of interfaces, so it can be coerced into any of the set of interfaces*/System.out.println (Subject.getclass (). GetName ()); }}

JAVA Dynamic Agent Learning record

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.