Java Dynamic Agent

Source: Internet
Author: User

has been on the dynamic agent is unfamiliar, always thought is very advanced things, like the reflection of Java, but really to achieve, it is so back, afraid of their own forgotten, so tidy up the thoughts, recorded here.

 Package Com.zhj;  Public  Interface Cat {//     Build Cat interface, before I was curious to change the interface to abstract class, when the proxy object is taken //     Appears classcastexception.     void Eat (int  num);      void sleep (int  hour);}

Implementation class:

 Package Com.zhj;  Public class Implements Cat {    publicvoid eat (int  num) {        System.out.println ("I eat" + num+ "fishes every Day");    }      Public void sleep (int  hour) {        System.out.println ("I Sleep" +hour+ "hours every day" );    }}

interface and implementation classes for inserting logs:

 Package Com.zhj;  Public Interface Logutil {    publicvoid  beforemethod ();      Public void testlazycat (int  sum);}
 PackageCom.zhj; Public classLogutilimpImplementsLogutil {@Override Public voidBeforemethod () {System.out.println ("Method Begin"); System.out.println ("---------------"); } @Override Public voidTestlazycat (intnum) {System.out.println ("---------------"); if(num>8) {System.out.println ("It is a lazy cat!"); }        Else{System.out.println ("It is a good cat!"); }    }}

Next is the play: Implement the Invocationhandle interface, there is only one invoke method, the internal use of reflection to complete the call to the method.

 PackageCom.zhj;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMyinvocationhandlerImplementsInvocationhandler {//prepare the target to proxy, which is used to inject the Proxied object    PrivateObject Target;  Public voidsettarget (Object target) { This. target=Target; } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {logutil lu=NewLogutilimp (); //call the log before the methodLu.beforemethod (); Java reflection, Target is the proxy object, args is the method passed in the parameter array objects object result=Method.invoke (target, args); //method to invoke the Log class method, and also to pass the parameters of the incoming methodLu.testlazycat ((Integer) args[0]); returnresult; }}
 PackageCom.zhj;ImportJava.lang.reflect.Proxy; Public classmyproxy { Public Staticobject GetProxy (object target) {//instantiating a custom handlerMyinvocationhandler handler=NewMyinvocationhandler (); //inject the Proxied objectHandler.settarget (target); //Build Proxy Object    returnproxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), handler); }}

Test:

 Package Com.zhj;  Public class Test {    publicstaticvoid  main (string[] args) {        // New one Lazycat        Cat target=New  lazycat ();         // get the agent "lazy cat", this lazy cat has not been lazy cat, each call a method, the method is added before and after the log        Cat cat=(CAT) Myproxy.getproxy (target);                Cat.sleep (n);            }}

Java Dynamic 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.