第一种获取代理方式:
Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Constructor constructor1 = clazzProxy.getConstructor(InvocationHandler.class);
class MyInvocationHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
return null;
}
}
Collection proxy1 = (Collection)constructor1.newInstance(new MyInvocationHandler());
System.out.println(proxy1+"hhh");
proxy1.clear();
Collection proxy2 = (Collection)constructor1.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
return null;
}
});
Collection proxy3 = (Collection)Proxy.newProxyInstance(
Collection.class.getClassLoader(),
new Class[]{Collection.class},
new InvocationHandler(){
ArrayList target = new ArrayList();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
Object retVal;
if(args!=null && args[0].equals("aaa")){
retVal = method.invoke(target, "abc");
}else{
retVal = method.invoke(target, args);
}
return retVal;
}
});
proxy3.add("aaa");
proxy3.add("bbb");
proxy3.add("ccc");
Iterator iterator = proxy3.iterator();
while(iterator.hasNext()){
String str = (String)iterator.next();
System.out.println(str);
}