import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
//实现接口
public class InvocationImpl implements InvocationHandler {
private ArrayList list = new ArrayList();
public InvocationImpl(ArrayList list) {
this.list = list;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object o = null;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(args[0])){
o = method.invoke(list, args[0]);
i--;
}
}
return o;
}
}
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
//对Collection接口的子类ArrayList进行代理,
// 以前的remove(Object obj)方法是删除集合中第一次出现的元素(比如集合中有多个“abc”,调用remove(“abc”)后只会删除一个元素)。
// 代理后,要求在调用remove(Object obj)方法后,能够删除集合中所有匹配的元素【动态代理】
public class Demo01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("abc");
arrayList.add("abc");
arrayList.add("abc");
arrayList.add("abd");
arrayList.add("abe");
arrayList.add("abcf");
//获得类加载器
ClassLoader classLoader = arrayList.getClass().getClassLoader();
//获得接口列表
Class<?>[] interfaces = arrayList.getClass().getInterfaces();
//实例化InvocationImpl将arrayList作为参数传递
InvocationImpl invocation = new InvocationImpl(arrayList);
List o = (List) Proxy.newProxyInstance(classLoader, interfaces, invocation);
o.remove("abc");
System.out.println(arrayList);
}
}
===================================================
package com.itheima.day15.home01;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
//对Collection接口的子类ArrayList进行代理,
// 以前的remove(Object obj)方法是删除集合中第一次出现的元素(比如集合中有多个“abc”,调用remove(“abc”)后只会删除一个元素)。
// 代理后,要求在调用remove(Object obj)方法后,能够删除集合中所有匹配的元素【动态代理】
public class Demo01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("abc");
arrayList.add("abc");
arrayList.add("abc");
arrayList.add("abd");
arrayList.add("abe");
arrayList.add("abcf");
ClassLoader classLoader = arrayList.getClass().getClassLoader();
Class<?>[] interfaces = arrayList.getClass().getInterfaces();
//使用匿名内部类对象
List o1 = (List) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object o = null;
if (method.getName().equals("remove")) {
while (arrayList.contains(args[0])) {
o = method.invoke(arrayList, args[0]);
}
}
return o;
}
});
o1.remove("abc");
System.out.println(arrayList);
}
}