Java Dynamic Agent code recently learned Java agent, it feels very magical, especially dynamic agent, the function is really powerful, if there is a dynamic agent, then the hacker is not a more development step ... Implementation of Java Dynamic Agent, the main implementation of several steps
1. Implement the Invocationhandler interface, and then implement the public object invoke (object proxy, Method M, object[] args) method, the code is as follows
Package Com.chapter1.dynamicproxy;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.Method; public class Proxyhandler implements Invocationhandler{private object Proxied;public Proxyhandler (object proxied) { this.proxied = proxied;} @Overridepublic object Invoke (object proxy, Method m, object[] args) throws Throwable {//TODO auto-generated Method Stubsy Stem.out.println ("before"); M.invoke (this.proxied, args); return null;}}
2. Application steps
Package Com.chapter1.dynamicproxy;import Java.lang.reflect.proxy;public class Test {public static void main (string[] args) {Realcoder rc = new Realcoder (); Proxyhandler ph = new Proxyhandler (RC); Coder PROXYC = (coder) proxy.newproxyinstance (Rc.getclass (). getClassLoader (), Rc.getclass (). Getinterfaces (), ph); Proxyc.coding ();}}
RC is the object that is being proxied, the ph is the object that you create, and then you create the proxy instance with a proxy and then call the method.
Java Dynamic Agent Code