Agent Mode-JDK Proxy
Using the JDK-supported proxy mode, dynamic proxy
The scenario is as follows: This example proxies the ArrayList, doing some extra work before and after each ArrayList operation.
Arraylistproxy class
Here is the implementation of the agent.
Import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;public class Arraylistproxy implements Invocationhandler { private Object proxy; Public arraylistproxy (Object obj) { this.proxy = obj; } @Override Public object Invoke (Object proxy, Method method, object[] args) throws Exception { System.out.println ("Before calling" + method); if (args! = null) {for (Object Arg:args) { System.out.println (arg);} } Object o = Method.invoke (this.proxy, args); System.out.println ("After calling" + method); return o; }}
Myutils class
Encapsulates the Proxy.newproxyinstance () method for easy access to proxy objects.
Import Java.lang.reflect.proxy;public class Myutils {public static Object getproxy (Object obj) { class cls = obj. GetClass (); Return Proxy.newproxyinstance ( cls.getclassloader (), cls.getinterfaces (), new Arraylistproxy (obj) ); }}
Main
Run the test here
Import Java.util.arraylist;import java.util.List; @SuppressWarnings ("Unchecked") public class Main {public static void Main (string[] args) { List reallist = new arraylist<string> (ten); List proxylist = (list) myutils.getproxy (reallist); Proxylist.add ("New"); System.out.print ("\ n"); Proxylist.add ("York");} }
Proxy mode-JDK proxy (Java implementation)