import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class Protest {
public static void addElement(Collection con) {
boolean flag = con.add("我要在这个集合里面添加元素,谁也拦不住,哈哈哈!!!"); //成功加进去
System.out.println(flag);
}
public static void main(String[] args) {
Collection con = (Collection) new ArrayListProxy().createProxy(new ArrayList());
addElement(con);
System.out.println(con.size());//size=1
}
}
class ArrayListProxy {
private Object target;
public Object getTarget() {
return target;
}
public Object createProxy(Object target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("小样,我是病毒,今天我就要阻止你了,爱咋咋地");//拦截到invoke方法,打印这一串东西
Object result = method.invoke(getTarget(), args);
return result;
}
});
}
}
转载:http://blog.csdn.net/xlinsist/article/details/41819493
}