动态代理 调用vector 函数:
vector实现List ,故抽象接口和真实角色 省略,这里只写 实现InvocationHandle的实现类 和 代理对象调用被代理函数的部分:
package com.Dynamic.Proxy.Vector;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class VectorProxy implements InvocationHandler {
private Object proxyy;
public VectorProxy(Object obj) {
this.proxyy = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("What Method is Using: "+method);
if(args!=null)
{
for(Object obj:args)
{
System.out.println(obj);
}
}
Object obj=method.invoke(proxyy, args);
return obj;
}
}
package com.Dynamic.Proxy.Vector;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Vector;
public class Client {
public static void main(String[] args) {
List<String> list = new Vector<String>();
VectorProxy handler = new VectorProxy(list);
List ProxyList=(List)Proxy.newProxyInstance(VectorProxy.class.getClassLoader(), list
.getClass().getInterfaces(), handler); //vector宣称实现的接口,代理对象ProxyList也继承它
Object obj=ProxyList.add("hello"); //add 的返回值为boolean
System.out.println(obj);
ProxyList.add(1,"yep");
}
}
输出:
What Method is Using: public abstract boolean java.util.List.add(java.lang.Object)
hello
true
What Method is Using: public abstract void java.util.List.add(int,java.lang.Object)
1
yep