欢迎来到天天文库
浏览记录
ID:13035384
大小:28.00 KB
页数:4页
时间:2018-07-20
《java动态代理dynamicproxy.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、java动态代理DynamicProxy1.被代理对象的接口:1packagetest.dynamicproxy;23publicinterfaceTargetInterface{4publicvoidSayHello();5publicintsum(inta,intb);6}2.被代理的对象:01packagetest.dynamicproxy;0203publicclassTargetimplementsTargetInterface{0405publicvoidSayHello(){06System.out.println(“Hello”);07}08publicintsu
2、m(inta,intb){09returna+b;10}11}3.InvocationHandler包装:01packagetest.dynamicproxy;0203importjava.lang.reflect.InvocationHandler;04importjava.lang.reflect.Method;0506publicclassTargetInvocationHandlerimplementsInvocationHandler{0708privateObjectobject;09publicTargetInvocationHandler(Objectobj){1
3、0this.object=obj;11}1213publicObjectinvoke(Objectproxy,Methodmethod,Object[]args2)14throwsThrowable15{16doBefore();17Objectresult=method.invoke(object,args2);18doAfter();19returnresult;20}2122publicvoiddoBefore(){23System.out.println(“dobefore”);24}2526publicvoiddoAfter(){27System.out.println
4、(“doafter”);28}29}4.测试类:01packagetest.dynamicproxy;0203importjava.lang.reflect.Proxy;0405publicclassTestDynamicProxy{0607/**08*@paramargs09*/10publicstaticvoidmain(String[]args){11Targett=newTarget();12TargetInvocationHandlerhandler=newTargetInvocationHandler(t);1314TargetInterfaceproxy=(Targ
5、etInterface)Proxy.newProxyInstance(15t.getClass().getClassLoader(),16t.getClass().getInterfaces(),17handler);1819proxy.SayHello();2021intb=proxy.sum(10,20);22System.out.println(b);23}2425}
此文档下载收益归作者所有