您的位置:首页 > 编程语言 > Java开发

JDK动态代理

2017-01-07 10:32 381 查看
InvocationHandler.java

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//实现InvocationHandler接口
public class ProxyInvocationHandler implements InvocationHandler {

private Object target; //接口

public void setTarget(Object target) {
this.target = target;
}

//返回指定接口的代理类的实现类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(), this);
}

/*
* proxy是代理类
* method是代理类的调用处理程序的方法对象
* 调用代理类实例的处理方法时,其实就是调用invoke方法
* */
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
for(Object arg:args){ //方法执行的参数
System.out.println(arg);
}
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String methodName){
System.out.println("执行"+methodName+"方法");
}
}
Client.java
public class Client {

public static void main(String[] args) {
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(new ArrayList());
List list = (List)pih.getProxy();//生成代理类
list.add("aaa"); //会调用InvocationHandler中的invoke方法
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: