对Collection接口的子类ArrayList进行代理,以前的remove(Object obj)方法是删除集合中第一次出现的元素(比如集合中有多个“abc”,调用remove(“abc”)后只会删除一个元素)。
代理后,要求在调用remove(Object obj)方法后,能够删除集合中所有匹配的元素【动态代理】
//创建被代理对象
ArrayList<String> list = new ArrayList<>();
//创建list代理对象
List proxyInstance = (List) Proxy.newProxyInstance(
//类加载器
ArrayList.class.getClassLoader(),
//父接口
list.getClass().getInterfaces(),
//处理器:拦截所执行的方法
new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//Object proxy:代理对象
//Method method:代理对象的执行方法对象
//Object[] args:方法中的参数
Object o = method.invoke(list, args);
String name = method.getName();
if (name.equals("remove")) {
list.removeIf(s -> s.equals(args[0]));
//迭代器方法:
/*Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
String s = iterator.next();
if(s.equals(args[0])) {
iterator.remove();
}
}*/
}
return o;
}
}
);
proxyInstance.add("abc");
proxyInstance.add("abcd");
proxyInstance.add("bvd");
proxyInstance.add("abc");
proxyInstance.remove("abc")