对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;
}
}
图片解析:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7e1987b6cc1dee26daacb18337176d34.png)