JAVA的动态代理分析

上传人:博****1 文档编号:467362926 上传时间:2023-12-13 格式:DOCX 页数:6 大小:18.68KB
返回 下载 相关 举报
JAVA的动态代理分析_第1页
第1页 / 共6页
JAVA的动态代理分析_第2页
第2页 / 共6页
JAVA的动态代理分析_第3页
第3页 / 共6页
JAVA的动态代理分析_第4页
第4页 / 共6页
JAVA的动态代理分析_第5页
第5页 / 共6页
点击查看更多>>
资源描述

《JAVA的动态代理分析》由会员分享,可在线阅读,更多相关《JAVA的动态代理分析(6页珍藏版)》请在金锄头文库上搜索。

1、JAVA的动态代理分析引导语:在使用动态代理类时,我们必须实现InvocationHandler 接口,以下是分享给大家的JAVA动态代理,欢迎 !1 ,被代理类的接口 ProxiedJava 代码packageTest1;/ 被代理类需实现的接口publicinterfaceProxiedvoiddoSomething();voiddoSomethingElse(Stringstr);2 ,一个 Proxied 接口的实现类(被代理类 )Java 代码packageTest1;publicclassConcreteProxiedimplementsProxiedOverridepublicv

2、oiddoSomething()tryThread.sleep(100);catch(InterruptedExceptione)System.err.println(Error:InterruptedException);System.out.println(this.getClass().getSimpleName()+doSomething.);OverridepublicvoiddoSomethingElse(Stringstr)tryThread.sleep(150);catch(InterruptedExceptione)System.err.println(Error:Inter

3、ruptedException);System.out.println(this.getClass().getSimpleName()+doSomethingElse,argument=+str+.);3 , TimingInvocationHandler 类,实现了 InvocationHandler接口Java 代码packageTest1;importjava.lang.reflect.InvocationHandler;importjava.lang.reflect.Method;publicclassTimeingInvocationHandlerimplementsInvocati

4、onHand ler/ 被代理的对象privateObjectproxied;publicTimeingInvocationHandler(Objectproxied)this.proxied=proxied;/ 参数 proxy 表示代理类的对象/ 参数method表示被代理类和代理类都实现的接口的方法对象/ 参数 args 表示方法 method 的参数数组OverridepublicObjectinvoke(Objectproxy,Methodmethod,Objectargs)throwsThrowableSystem.out.println(method.getDeclaringCl

5、ass().getName();longcurrentTimeMillis=System.currentTimeMillis();Objectret=method.invoke(proxied,args);System.out.println(this.getClass().getSimpleName()+waste stime:+(System.currentTimeMillis()-currentTimeMillis)+ms);returnret;4 ,测试类 TestJava 代码packageTest1;importjava.lang.reflect.Proxy;publicclass

6、TestProxypublicstaticvoidmain(Stringargs)Proxiedproxied=newConcreteProxied();proxied.doSomething();proxied.doSomethingElse(onlyaString);/ 生成一个代理实例,这个代理实现了 Proxied 接口/ 对这个代理(proxy) 的方法的调用会重定向到TimeingInvocationHandler 的 invoke 方法Proxiedproxy=(Proxied)Proxy.newProxyInstance(Proxied.class.getClassLoader

7、(),/类加载器newClassProxied.class,/ 代理要实现的接口newTimeingInvocationHandler(proxied)/ 调用处理器);proxy.doSomething();proxy.doSomethingElse(onlyaString);运行 Test 类,输出如下:ConcreteProxieddoSomething.ConcreteProxieddoSomethingElse,argument=onlyaString.Test1.ProxiedConcreteProxieddoSomething.TimeingInvocationHandlerwastestime:110msTest1.ProxiedConcreteProxieddoSomethingElse,argument=onlyaString.TimeingInvocationHandlerwastestime:156ms

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 商业/管理/HR > 营销创新

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号