代理类需实现InvocationHandler接口:

public interface InvocationHandler
{
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable;
}

其中参数:

proxy - 在其上调用方法的代理实例
method - 对应于在代理实例上调用的接口方法的 Method 实例。Method 对象的声明类将是在其中声明方法的接口,该接口可以是代理类赖以继承方法的代理接口的超接口。
args - 包含传入代理实例上方法调用的参数值的对象数组,如果接口方法不使用参数,则为 null。

返回值是从代理实例的方法调用返回的值。

运行时代理对象的产生(一般转换为接口使用):
Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), invocationHandler)

target.getClass().getClassLoader() - 代理类的类加载器
target.getClass().getInterfaces() - 代理类要实现的接口列表
invocationHandler - 实现了InvocationHandler的类的实例(方法调用的调用处理程序)

调用接口所声明的代理对象的方法时即调用了实现InvocationHandler接口的类的invoke方法(InvocationHandler接口成员)

动态代理是Spring AOP实现的原理,常用于异常,日志,性能检测,权限,事务

示例代码:

//UserProxy.Java

package com.xpp.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class UserProxy implements InvocationHandler { private Object target;//被代理对象 public Object bind(Object target) {
this.target = target; return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
} @Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null; System.out.println(method.getName() + " call is starting"); result = method.invoke(target, args); System.out.println(method.getName() + " call ended");
return result;
}
}
//Client.Java
package com.xpp.client; import com.xpp.dao.UserDAO;
import com.xpp.dao.impl.UserDAOFileImpl;
import com.xpp.model.User;
import com.xpp.proxy.UserProxy; public class Client {
public static void main(String[] args) {
UserProxy up = new UserProxy();
UserDAO ud = (UserDAO) up.bind(new UserDAOFileImpl());
ud.AddUser(new User());
}
}

最新文章

  1. CI框架搭建
  2. JavsScript+dom
  3. easyui-textbox回车事件
  4. 李洪强iOS经典面试题144-数据存储
  5. tomcat切割日志的shell脚本
  6. POJ 3299 Humidex 难度:0
  7. The difference between macro and function I/Ofunction comparision(from c and pointer )
  8. 浅谈Objective—C中的面向对象特性
  9. hdu 3336 Count the string KMP+DP优化
  10. Java中遍历Map的几种方法
  11. 自学HTML5第四节(canvas画布详解)
  12. 5 MySQL索引
  13. 通用性站点管理后台(Bee OPOA Platform)
  14. ubuntu14.04下手动安装eclipse
  15. 2017-5-18 Repeater 重复器的使用
  16. HDU1300 Pearls
  17. 通用后台管理系统UI-AdminLTE:构造动态菜单栏
  18. java thread yield 的设计目的是什么?
  19. Windbg分析蓝屏Dump文件
  20. WMI设置有线网卡IP地址

热门文章

  1. IntelliJ IDEA调整控制台输出字体大小
  2. JQuery上传插件uploadify整理(Events)
  3. document.styleSheets[0]是个啥
  4. winform异步进度条LongTime
  5. Cocos2d-x下Lua调用自定义C++类和函数的最佳实践[转]
  6. WEB前端研发工程师编程能力成长之路(1)(转)
  7. 关于NopCommerce3.6版的@Html.Widget(“home_page_top”)的说明
  8. 慕课网-安卓工程师初养成-2-6 Java中的数据类型
  9. socket学习笔记——select与epoll函数的使用(linux)
  10. Android 操作系统的内存回收机制