Proxy 示例

 1 package cn.proxy03;
 2 
 3 import java.lang.reflect.InvocationHandler;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Proxy;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 /**
 9  * 用代理修改list的add方法  判断添加字符串的首字母是否为J开始
10  * @author ASUS
11  *
12  */
13 public class ListProxy {
14 
15     public static void main(String[] args) {
16         //声明被代理的对象
17         final List<String> list = new ArrayList<>();
18         Object object = Proxy.newProxyInstance(ListProxy.class.getClassLoader(),
19                 new Class[]{List.class},
20                 new InvocationHandler() {
21                     
22                     @Override
23                     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
24                         // 限制:如果调用的是add方法,如果添加的是J则接收
25                         if(method.getName().equals("add")){
26                             if(args[0].toString().startsWith("J")){
27                                 list.add(args[0].toString());
28                                 return true;
29                             }else{
30                                 System.err.println("不接受");
31                                 return false;
32                             }
33                         }else{
34                             return method.invoke(list, args);
35                         }
36                     }
37                 });
38         List<String> listAdd = (List<String>) object;
39         new ListProxy().add(listAdd);
40     }
41     
42     public void add(List<String> list){
43         list.add("Jack");
44         list.add("Mary");
45         System.err.println("J开头的字符串个数为:"+list.size());
46     }
47 }

运行结果

posted @ 2016-06-07 20:50  追梦人丶  阅读(185)  评论(0编辑  收藏  举报