动态代理小案例

对Collection接口进行代理,以前的remove(Object obj)方法是删除集合中第一次出现的元素(比如集合中有多个“abc”,调用remove(“abc”)后只会删除一个元素)。代理后,要求在调用remove(Object obj)方法后,能够删除集合中所有匹配的元素。【动态代理】

注意:remove(Object obj)方法的返回值类型原本是boolean类型,所以代理对象需要和原方法返回一样的类型。

代码:
方法1:
public class Demo {
    public static void main(String[] args) {
        Collection<String> coll = new ArrayList<>();
        coll.add("石原里美");
        coll.add("新垣结衣");
        coll.add("花泽香菜");
        coll.add("斋藤飞鸟");
        coll.add("斋藤飞鸟");
        coll.add("斋藤飞鸟");

        Collection<String> coll2 = MyCollections.method(coll);
        coll2.remove("斋藤飞鸟");

        System.out.println(coll2);
    }
}


public class MyCollections {
    public static Collection<String> method(Collection<String> coll){
        Collection coll2 =(Collection) Proxy.newProxyInstance(coll.getClass().getClassLoader(), coll.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("remove")){
                    boolean b = true;
                    while (b){
                        b=(boolean)method.invoke(coll,args);
                    }
                    return b;
                }
                Object o = method.invoke(coll, args);
                return o;
            }
        });
        return coll2;
    }
}
方法2:
public class MyCollections {
    public static Collection<String> getMethod(Collection<String> coll){
        Collection coll2 = (Collection)Proxy.newProxyInstance(coll.getClass().getClassLoader(), coll.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                int count = 0;
                if (method.getName().equals("remove")){
                    while (coll.contains(args[0])){
                        count++;
                        method.invoke(coll, args);
                    }
                    return count !=0;
                }
                Object invoke = method.invoke(coll, args);
                return invoke;
            }
        });
        return coll2;
    }
}
图片解析:

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值