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