《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