码迷,mamicode.com
首页 > 其他好文 > 详细

动态代理

时间:2018-03-06 15:38:46      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:动态代理

public class TextApp { @Test public void demo01(){ // 类 = new 类 UserServiceImpl userService = new UserServiceImpl(); } @Test public void demo02(){ // 接口 = new 类 UserService userService = new UserServiceImpl(); } /* 静态代理(装饰者)和动态代理 都具有相同的约束条件 * * 使用前提:必须有接口 * */ @Test public void demo03(){ //实现类 (目标类) UserService userService = new UserServiceImpl(); //1 参数1:ClassLoader 类加载器,用于将类加载到内存 // * 格式:当前类名.class.getClassLoader() //2 参数2:需要实现的所有接口 // * 格式1:new Class[] { 接口.class } // * 格式2:userService.getClass().getInterfaces() ,目标类上的所有接口 //3 参数3:InvocationHandler 执行处理类 // * 代理类的每一个方法被调用时,都将执行处理类的invoke()方法 // * invoke参数1:Object proxy ,代理类本身,一般没有 // * invoke参数2:Method method,当前执行的方法 // * invoke参数3:Object[] args,当前执行方法的实际参数 //编写代理类(增强) UserService proxyService = (UserService)Proxy.newProxyInstance( TextApp.class.getClassLoader(), new Class[]{ UserService.class }, new MyInvocationHandler( userService )); //入口:使用从代理类获得内容 proxyService.addUser(); proxyService.updateUser(); } } class MyInvocationHandler implements InvocationHandler { private UserService userService; public MyInvocationHandler(UserService userService) { this.userService = userService; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //System.out.println("aaaa" + method.getName()); //执行目标类的方法 return method.invoke(userService, args); } }

动态代理

标签:动态代理

原文地址:http://blog.51cto.com/13579086/2083451

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!