代理模式-JDK Proxy(Java实现)
代理模式-JDK Proxy
使用JDK支持的代理模式, 动态代理
场景如下: 本文例子代理了ArrayList, 在ArrayList每次操作时, 在操作之前和之后都进行一些额外的操作.
ArrayListProxy类
这里是代理的实现.
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类
封装了Proxy.newProxyInstance()方法, 方便取得代理对象.
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
在这里进行运行测试
import java.util.ArrayList; import java.util.List; @SuppressWarnings("unchecked") public class Main { public static void main(String[] args) { List realList = new ArrayList<String>(10); List proxyList = (List) MyUtils.getProxy(realList); proxyList.add("New"); System.out.print("\n\n"); proxyList.add("York"); } }
相关推荐
windle 2020-10-29
tinydu 2020-08-03
标题无所谓 2020-06-26
程序员俱乐部 2020-06-08
薛正华 2020-05-30
itmale 2020-05-26
fangxiaoji 2020-05-12
横云断岭 2020-04-26
hygbuaa 2020-04-23
wanghongsha 2020-04-09
sicceer 2020-02-23
liym 2020-02-13
zllbirdonland 2020-01-11
chenjia00 2020-01-07
paopao00 2020-01-07
hygbuaa 2020-01-01