资源预览内容
第1页 / 共6页
第2页 / 共6页
第3页 / 共6页
第4页 / 共6页
第5页 / 共6页
第6页 / 共6页
亲,该文档总共6页全部预览完了,如果喜欢就下载吧!
资源描述
JAVA的动态代理分析引导语:在使用动态代理类时,我们必须实现InvocationHandler 接口,以下是分享给大家的JAVA动态代理,欢迎 !1 ,被代理类的接口 ProxiedJava 代码packageTest1;/ 被代理类需实现的接口publicinterfaceProxiedvoiddoSomething();voiddoSomethingElse(Stringstr);2 ,一个 Proxied 接口的实现类(被代理类 )Java 代码packageTest1;publicclassConcreteProxiedimplementsProxiedOverridepublicvoiddoSomething()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:InterruptedException);System.out.println(this.getClass().getSimpleName()+doSomethingElse,argument=+str+.);3 , TimingInvocationHandler 类,实现了 InvocationHandler接口Java 代码packageTest1;importjava.lang.reflect.InvocationHandler;importjava.lang.reflect.Method;publicclassTimeingInvocationHandlerimplementsInvocationHand ler/ 被代理的对象privateObjectproxied;publicTimeingInvocationHandler(Objectproxied)this.proxied=proxied;/ 参数 proxy 表示代理类的对象/ 参数method表示被代理类和代理类都实现的接口的方法对象/ 参数 args 表示方法 method 的参数数组OverridepublicObjectinvoke(Objectproxy,Methodmethod,Objectargs)throwsThrowableSystem.out.println(method.getDeclaringClass().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;publicclassTestProxypublicstaticvoidmain(Stringargs)Proxiedproxied=newConcreteProxied();proxied.doSomething();proxied.doSomethingElse(onlyaString);/ 生成一个代理实例,这个代理实现了 Proxied 接口/ 对这个代理(proxy) 的方法的调用会重定向到TimeingInvocationHandler 的 invoke 方法Proxiedproxy=(Proxied)Proxy.newProxyInstance(Proxied.class.getClassLoader(),/类加载器newClassProxied.class,/ 代理要实现的接口newTimeingInvocationHandler(proxied)/ 调用处理器);proxy.doSomething();proxy.doSomethingElse(onlyaString);运行 Test 类,输出如下:ConcreteProxieddoSomething.ConcreteProxieddoSomethingElse,argument=onlyaString.Test1.ProxiedConcreteProxieddoSomething.TimeingInvocationHandlerwastestime:110msTest1.ProxiedConcreteProxieddoSomethingElse,argument=onlyaString.TimeingInvocationHandlerwastestime:156ms
收藏 下载该资源
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号