Java Dynamic Agent code quick to get started

Source: Internet
Author: User

The two core points of a dynamic agent are: The behavior of the agent and the agency.

To give an example, when I went to college, many students ate lunch when they called others to bring rice, there is a person H special warm-hearted, think of a way, he hung a sign at the door, every day who want to bring food to write the bulletin board to write their own want to eat rice, H every time who want to eat what rice and then go to help everyone buy rice This is the process of a typical agent. Acting here is the act of bringing rice, the agency is H. And the agency behavior and the agency to understand the coupling between.

Below, we use the proxy mechanism provided by the JDK to implement the code based on this example.

First, we create a proxy behavior class interface Buylunchint (because there may be a lot of people who need to bring rice and have different meals for inheritance implementations)

 Package proxy; /**  */Publicinterface  buylunchint    {void  buylunch ();}
View Code

Next, we implement agent mechanism based on Agent behavior Interface (the implementation of Agency is the core)

    • The main use of the two reflection package of two classes, Invocationhandler and proxy class.
    • Proxy class creates agent instances from incoming class information
    • Invocationhandler implementation of Proxy instance method by implementing Invoke method
 Packageproxy;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;/*** @Author Darrenqiao * Agent-based Behavior interface implementation of the proxy class * main work two parts: * Create proxy instance through proxy * Implement proxy behavior by overriding the Invoke method of the Invocationhandler class*/ Public classProxyagentImplementsInvocationhandler {PrivateObject Target;  Publicobject Create (object target) { This. target =Target; returnProxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), This); }    //implement proxy mechanism, invoke method based on interface by reflection@Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Look who wants my help with the meal.");        Method.invoke (target, args); System.out.println ("Now, your meal."); return NULL; }}
View Code

Then, is the people who need to bring rice, with what meal, on the implementation of interface Buylunchint and written to bulletin board Configure.properties

 Package proxy; /**  */Publicclassimplements  buylunchint    {    @Override  Public void Buylunch () {        System.out.println ("Darren to eat Fried rice");}    }
View Code
Class=proxy. Darrenbuylunch
View Code

Finally, in the main method, a few steps, first look at the bulletin board configure.properties on the need for proxy objects, there is the creation of agents and agent execution; no, quit.

ImportProxy. Buylunchint;ImportProxy. proxyagent;ImportJava.io.*;Importjava.util.Properties;/*** @Author Darrenqiao*/ Public classMain {StaticProperties prop =NewProperties (); Static voidinit () {Try {            //This initializes the class that needs to be proxiedInputStream InputStream =NewBufferedinputstream (NewFileInputStream ("C:\\zongpengq\\code\\testdynamicproxy\\src\\configure.properties"));        Prop.load (InputStream); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }     Public Static voidMain (string[] args)throwsclassnotfoundexception, illegalaccessexception, instantiationexception {init (); if(prop.size () = = 0) {System.out.println ("No one's going to bring dinner today."); return; }        //Create an agencyProxyagent proxyagent =Newproxyagent ();  for(String S:prop.stringpropertynames ()) {string ClassName=Prop.getproperty (s); Class ClassInfo=Class.forName (className); //To create a specific proxy objectBuylunchint Buylunch =(Buylunchint) classinfo.newinstance (); //Agents Create proxy instances for proxy objects (similar to: Arrange a personal agent for you to do this)Buylunchint proxy =(Buylunchint) proxyagent.create (buylunch); //Agent to do thingsProxy.buylunch (); }    }}
View Code

We look at the results of the operation, if no one needs to bring rice (that is, to empty the bulletin board configure.properties), the results are as follows

If someone needs to bring a meal, such as Darren, configured in Configure.properties, the results are as follows

Java Dynamic Agent code quick to get started

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.