动态代理的实现可以说是静态代理的一种模式升级,如果还有同学不知道代理模式的概念可以参考我的前一篇文章http://blog.csdn.net/u012481172/article/details/50157079; 下面我们分四步走来讲解一下动态代理如何使用:
一、定义一个行为规范
public interface IService {
public String doSomething();
}
以上接口只需要由目标对象实现即可,因为我们现在不需要自己去创建代理,而是由JDK动态生成代理的。
二、实现自己的InvocationHandler
public class MyInvocationHandler implements InvocationHandler {
// 目标对象
private Object target;
public MyInvocationHandler(Object target) {
super();
this.target = target;
}
/**
* 此方法是实现了InvocationHandler的方法
* 是目标对象方法调用
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("在目标对象执行之前我先做一些事情...");
// 执行目标对象的方法
Object result = method.invoke(target, args);
System.out.println("在目标对象执行之后我再做一些事情...");
return result;
}
/**
* 获取目标对象的代理对象
*
* @return 代理对象
*/
public Object getProxy() {
return Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), target.getClass().getInterfaces(),
this);
}
}
以上就是实现了自己的InvocationHandler,这基本上就是一个规范的写法了,之后如果我们需要创建自己的InvocationHandler,就都按照此格式来。注意在getProxy()方法中,用到了Proxy类,该类是JDK下的一个系统类,并不是我上一篇文章自己的Proxy类。
三、实现目标对象
public class RealService implements IService {
public String doSomething() {
System.out.println("目标对象正在做一些事情...");
return "目标对象正在做一些事情...";
}
}
四、目标对象的使用及打印测试
public static void main(String[] args) {
// 实例化目标对象
IService userService = new RealService();
// 实例化InvocationHandler
MyInvocationHandler invocationHandler = new MyInvocationHandler(
userService);
// 根据目标对象生成代理对象
IService proxy = (IService) invocationHandler.getProxy();
// 调用代理对象的方法
proxy.doSomething();
}
//================== 以下为打印结果
在目标对象执行之前我先做一些事情...
目标对象正在做一些事情...
在目标对象执行之后我再做一些事情...
五、相关资料
(1)关于动态代理的好处与应用场景:请移步至http://www.zhihu.com/question/20794107;
(2)关于Java动态代理的详细实现:请移步至:http://rejoy.iteye.com/blog/1627405;