public class ArraryListProxy {
List list = new ArrayList();
public List getProxy(){
return (List)Proxy.newProxyInstance(ArrayList.class.getClassLoader(),
ArrayList.class.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.toString().contains("remove"))
{
System.err.println("抱歉,你不能使用"+method.getName()+"方法");
return null;
}
Object obj = method.invoke(list, args);
return obj;
}
});
}
}
class TestProxy{
public static void main(String[] args) {
ArraryListProxy proxy = new ArraryListProxy();
List listProxy = proxy.getProxy();
listProxy.add("Tom");
listProxy.add("Jack");
listProxy.add("Bety");
System.out.println(listProxy);
listProxy.remove(2);//1
System.out.println(listProxy);//2
}
}
输出结果:
代理的执行过程:先通过Proxy的静态方法newProxyInstance生成代理对象,然后调用代理对象的add方法,调用InvocationHandler对象的invoke方法,通过反射调用真实对象的add方法。
存在的问题:代码中1和2处的执行顺序不是固定的,有待继续研究。