607的彩的正确网址

现在的位置: 607的彩的正确网址 > 编程语言 > 正文

深入学习Java动态代理

2020年02月14日 编程语言 ⁄ 共 12648字 ⁄ 字号 评论关闭

前言

607的彩的正确网址yaoxianglejiejavadongtaidaili,shouxianyaolejieshenmejiaozuodaili,shuxishejimoshidepengyouyidingzhidaozaigofzongjiede23zhongshejimoshizhong,youyizhongjiaozuodaili(proxy)deduixiangjiegouxingmoshi,dongtaidailizhongdedaili,zhidejiushizheizhongshejimoshi。

607的彩的正确网址zaiwokanlaisuoweidedailimoshi,he23zhongshejimoshizhongde“zhuangshimoshi”shiyigedongxi。23zhongshejimoshizhongjiangtamenzuoweiliangzhongmoshi,wangshangyeyouxiewenzhangjiangzheiliangzhongmoshideyitong,congxijielaikan,queshikeyirenweidiqufenzheiliangzhongmoshi,danshichouxiangdaoyidinggaoduhou,worenweizheiliangzhongmoshishiwanquanyiyangde。yincixuehuiledailimoshi,yejiutongshizhangwolezhuangshimoshi。

代理模式

607的彩的正确网址dailimoshijiandanlaishuo,jiushiduiyigeduixiangjinxingbaozhuang,baozhuanghoushengchengdeduixiangjuyouheyuanduixiangyiyangdefangfaliebiao,danshimeigefangfadoukeyishibeibaozhuangguode。

静态代理

607的彩的正确网址rangwomenxianlaikanyiduandaima:

package common;public class test {static interface subject{void sayhi();void sayhello();}static class subjectimpl implements subject{@overridepublic void sayhi() {system.out.println("hi");}@overridepublic void sayhello() {system.out.println("hello");}}static class subjectimplproxy implements subject{private subject target;public subjectimplproxy(subject target) {this.target=target;}@overridepublic void sayhi() {system.out.print("say:");target.sayhi();}@overridepublic void sayhello() {system.out.print("say:");target.sayhello();}}public static void main(string[] args) {subject subject=new subjectimpl();subject subjectproxy=new subjectimplproxy(subject);subjectproxy.sayhi();subjectproxy.sayhello();}}

607的彩的正确网址zheiduandaimazhongshouxiandingyileyigesubjectjiekou,jiekouzhongyoulianggefangfa。

607的彩的正确网址ranhoudingyilesubjectimplleishixiansubjectjiekoubingshixianqizhongdelianggefangfa,daozheilikendingshimeiwentide。

xianzaizaidingyiyigesubjuectimplproxylei,yeshixiansubjectjiekou。zheigesubjectimplproxyleidezuoyongshibaozhuangsubjectimplleideshili,tadeneibudingyiyigebianliangtargetlaibaocunyigesubjectimpldeshili。subjectimplproxyyeshixianlejiekouguidingdelianggefangfa,bingqiezaitadeshixianbanbenzhong,doudiaoyonglesubjectimpldeshixian,danshiyoutianjialezijidechuliluoji。

607的彩的正确网址xiangxinzheiduandaimabunanlijie,tatongguoduisubjectimpljinxingbaozhuang,dadaolejishuchuneirongtianjiaqianzhuidegongneng。zheizhongdailifangshijiaozuojingtaidaili。

动态代理

607的彩的正确网址congshangmiandeyanshizhongwomenbunankanchujingtaidailidequedian:womenduisubjectimpldelianggefangfa,shijinxingdexiangtongdebaozhuang,danshiqueyaozaisubjectimplproxylibaxiangtongdebaozhuangluojixieliangci,erqieyihouruguosubjectjiekouzaitianjiaxindefangfa,subjectimplproxyyebixuyaotianjiaxindeshixian,jinguansubjectimplproxyduisuoyoufangfadebaozhuangkenengdoushiyiyangde。

xiamianwobashangmianlizidejingtaidailigaichengdongtaidaili,womenlaikanyixiaqubie:

607的彩的正确网址package common;import java.lang.invoke.methodhandle;import java.lang.reflect.invocationhandler;import java.lang.reflect.method;import java.lang.reflect.proxy;public class test {static interface subject{void sayhi();void sayhello();}static class subjectimpl implements subject{@overridepublic void sayhi() {system.out.println("hi");}@overridepublic void sayhello() {system.out.println("hello");}}static class proxyinvocationhandler implements invocationhandler{private subject target;public proxyinvocationhandler(subject target) {this.target=target;}@overridepublic object invoke(object proxy, method method, object[] args) throws throwable {system.out.print("say:");return method.invoke(target, args);}}public static void main(string[] args) {subject subject=new subjectimpl();subject subjectproxy=(subject) proxy.newproxyinstance(subject.getclass().getclassloader(), subject.getclass().getinterfaces(), new proxyinvocationhandler(subject));subjectproxy.sayhi();subjectproxy.sayhello();}}

607的彩的正确网址zhikanmainfangfadehua,zhiyoudierxinghezhiqiandejingtaidailibutong,tongyangshishengchengyigesubjectproxydailiduixiang,zhishishengchengdedaimabutongle。jingtaidailishizhijienew yigesubjectimplproxydeshili,erdongtaidailizediaoyonglejava.lang.reflect.proxy.newproxyinstance()fangfa,womenlaikanyixiazheigefangfadeyuanma:

607的彩的正确网址public static object newproxyinstance(classloader loader,class<?>[] interfaces,invocationhandler h)throws illegalargumentexception{if (h == null) {throw new nullpointerexception();}/** look up or generate the designated proxy class.*/class<?> cl = getproxyclass(loader, interfaces);  //huoqudailileideclass/** invoke its constructor with the designated invocation handler.*/try {constructor cons = cl.getconstructor(constructorparams);  //constructorparamsshixieside:{ invocationhandler.class },shangbianfanhuidedailileiclassyidingshiextends proxyde,erproxyyouyigecanshuweiinvocationhandlerdegouzaohanshureturn cons.newinstance(new object[] { h });  //zheilitongguogouzaohanshujiangwomenzijidingyideinvocationhandlerdezileichuandaodailileideshilili,dangwomendiaoyongdailileiderenhefangfashi,shijishangdouhuidiaoyongwomendingyideinvocationhandlerzileizhongxiedeinvoke()hanshu} catch (nosuchmethodexception e) {throw new internalerror(e.tostring());} catch (illegalaccessexception e) {throw new internalerror(e.tostring());} catch (instantiationexception e) {throw new internalerror(e.tostring());} catch (invocationtargetexception e) {throw new internalerror(e.tostring());}}

shangmiande class<?> cl = getproxyclass(loader, interfaces); diaoyongdegetproxyclassfangfa:

public static class<?> getproxyclass(classloader loader,class<?>... interfaces)throws illegalargumentexception{if (interfaces.length > 65535) {  //yinweizaiclasswenjianzhong,yigeleibaocundejiekoushuliangshiyong2gezijielaibiaoshide,yincijavazhongyigeleizuiduokeyishixian65535gejiekouthrow new illegalargumentexception("interface limit exceeded");}class<?> proxyclass = null;/* collect interface names to use as key for proxy class cache */string[] interfacenames = new string[interfaces.length];// for detecting duplicatesset<class<?>> interfaceset = new hashset<>();     //yanzhenginterfaceslidejiekoushifounengbeileijiazaiqijiazai,shifoushijiekou,shifouyouzhongfude for (int i = 0; i < interfaces.length; i++) {/** verify that the class loader resolves the name of this* interface to the same class object.*/string interfacename = interfaces[i].getname();class<?> interfaceclass = null;try {interfaceclass = class.forname(interfacename, false, loader);} catch (classnotfoundexception e) {}if (interfaceclass != interfaces[i]) {throw new illegalargumentexception(interfaces[i] + " is not visible from class loader");}/** verify that the class object actually represents an* interface.*/if (!interfaceclass.isinterface()) {throw new illegalargumentexception(interfaceclass.getname() + " is not an interface");}/** verify that this interface is not a duplicate.*/if (interfaceset.contains(interfaceclass)) {throw new illegalargumentexception("repeated interface: " + interfaceclass.getname());}interfaceset.add(interfaceclass);interfacenames[i] = interfacename;}/** using string representations of the proxy interfaces as* keys in the proxy class cache (instead of their class* objects) is sufficient because we require the proxy* interfaces to be resolvable by name through the supplied* class loader, and it has the advantage that using a string* representation of a class makes for an implicit weak* reference to the class.*/list<string> key = arrays.aslist(interfacenames);  //shiyonginterfacesliebiaozuoweikeyhuancunzaicacheli,yejiushishixianlexiangtonginterfacesdedailileizhihuichuangjianjiazaiyici/** find or create the proxy class cache for the class loader.*/map<list<string>, object> cache;synchronized (loadertocache) {cache = loadertocache.get(loader);if (cache == null) {cache = new hashmap<>();loadertocache.put(loader, cache);}/** this mapping will remain valid for the duration of this* method, without further synchronization, because the mapping* will only be removed if the class loader becomes unreachable.*/}/** look up the list of interfaces in the proxy class cache using* the key. this lookup will result in one of three possible* kinds of values:* null, if there is currently no proxy class for the list of* interfaces in the class loader,* the pendinggenerationmarker object, if a proxy class for the* list of interfaces is currently being generated,* or a weak reference to a class object, if a proxy class for* the list of interfaces has already been generated.*/     //kankanhuancunliyoumeiyou,ruguoyoujiuzhijiequchulairanhoureturn,fouzepanduangenjupendinggenerationmarkerpanduanshifouyouqitaxianchengzhengzaishengchengdangqiandedaililei,ruguoyouzecache.wait()dengdai,ruguomeiyouzechuangjian。synchronized (cache) {/** note that we need not worry about reaping the cache for* entries with cleared weak references because if a proxy class* has been garbage collected, its class loader will have been* garbage collected as well, so the entire cache will be reaped* from the loadertocache map.*/do {object value = cache.get(key);if (value instanceof reference) {proxyclass = (class<?>) ((reference) value).get();}if (proxyclass != null) {// proxy class already generated: return itreturn proxyclass;} else if (value == pendinggenerationmarker) {// proxy class being generated: wait for ittry {cache.wait();} catch (interruptedexception e) {/** the class generation that we are waiting for should* take a small, bounded time, so we can safely ignore* thread interrupts here.*/}continue;} else {/** no proxy class for this list of interfaces has been* generated or is being generated, so we will go and* generate it now. mark it as pending generation.*/cache.put(key, pendinggenerationmarker);break;}} while (true);}     //querenyaoshengchengdedailileisuoshudebao,ruguointerfaceslisuoyoujiekoudoushipublicde,dailileisuoshubaojiushimorenbao;ruguoyouinterfacebushipublic,neimesuoyoubushipublicdeinterfacebixuzaiyigebaolifouzebaocuo。try {string proxypkg = null; // package to define proxy class in/** record the package of a non-public proxy interface so that the* proxy class will be defined in the same package. verify that* all non-public proxy interfaces are in the same package.*/for (int i = 0; i < interfaces.length; i++) {int flags = interfaces[i].getmodifiers();if (!modifier.ispublic(flags)) {string name = interfaces[i].getname();int n = name.lastindexof('.');string pkg = ((n == -1) ? "" : name.substring(0, n + 1));if (proxypkg == null) {proxypkg = pkg;} else if (!pkg.equals(proxypkg)) {throw new illegalargumentexception("non-public interfaces from different packages");}}}if (proxypkg == null) { // if no non-public proxy interfaces,proxypkg = ""; // use the unnamed package}{/** choose a name for the proxy class to generate.*/long num;synchronized (nextuniquenumberlock) {num = nextuniquenumber++;}string proxyname = proxypkg + proxyclassnameprefix + num;  //shengchengdailileidemingzi,proxypkgshishangmianquedingxialaidedailileisuozaidebaoming,proxyclassnameprefixshixiesidezifuchuan“$proxy”,numshiyigequanjuweiyidelongxingshuzi,cong0kaishileiji,meicishengchengxindedailileijiu+1,congzheiliyenengkanchushengchengdedongtaidailileideshuliangbunengchaoguolong.maxvalue/** verify that the class loader hasn't already* defined a class with the chosen name.*//** generate the specified proxy class.*/byte[] proxyclassfile = proxygenerator.generateproxyclass(proxyname, interfaces);  //shengchengyigeyiproxynameweileimingde,shixianleinterfaceslisuoyoujiekoudeleidezijiematry {proxyclass = defineclass0(loader, proxyname,proxyclassfile, 0, proxyclassfile.length);  //jiazaishengchengdelei} catch (classformaterror e) {/** a classformaterror here means that (barring bugs in the* proxy class generation code) there was some other* invalid aspect of the arguments supplied to the proxy* class creation (such as virtual machine limitations* exceeded).*/throw new illegalargumentexception(e.tostring());}}// add to set of all generated proxy classes, for isproxyclassproxyclasses.put(proxyclass, null);} finally {/** we must clean up the "pending generation" state of the proxy* class cache entry somehow. if a proxy class was successfully* generated, store it in the cache (with a weak reference);* otherwise, remove the reserved entry. in all cases, notify* all waiters on reserved entries in this cache.*/       //chuangjianchenggong,zejiangcachezhonggaikeydependinggenerationmarkertihuanweishijidedailileideruoyinyong,fouzeyeyaoqingchupendinggenerationmarkerbiaoji;buguanshifouchenggong,douyaozhixingcache.notifyall(),rangqitayaochuangjianxiangtongdailileibingqiezhixinglecache.wait()dexianchenghuifuzhixing。synchronized (cache) {if (proxyclass != null) {cache.put(key, new weakreference<class<?>>(proxyclass));} else {cache.remove(key);}cache.notifyall();}}return proxyclass; //zuihoufanhuidailileiclass}

607的彩的正确网址daozheili,womenyijingbadongtaidailidejavayuandaimadoujiexiwanle,xianzaisilujiuhenqingxile:

607的彩的正确网址proxy.newproxyinstance(classloader loader,class<?>[] interfaces,invocationhandler h) fangfajiandanlaishuozhixingleyixiacaozuo:

607的彩的正确网址1.shengchengyigeshixianlecanshuinterfaceslisuoyoujiekouqiejichengleproxydedailileidezijiema,ranhouyongcanshulideclassloaderjiazaizheigedaililei。

2.shiyongdailileifuleidegouzaohanshu proxy(invocationhandler h)laichuangzaoyigedailileideshili,jiangwomenzidingyideinvocationhandlerdezileichuanru。

3.fanhuizheigedailileishili,yinweiwomengouzaodedailileishixianleinterfaces(yejiushiwomenchengxuzhongchuanrudesubject.getclass().getinterfaces())lidesuoyoujiekou,yincifanhuidedailileikeyiqiangzhuanchengsubjectleixinglaidiaoyongjiekouzhongdingyidefangfa。

607的彩的正确网址xianzaiwomenzhidaoleyongproxy.newproxyinstance()fanhuidesubjectproxykeyichenggongqiangzhuanchengsubjectleixinglaidiaoyongjiekouzhongdingyidefangfale,neimezaidiaoyongfangfahou,dailileishilizenmejinxingchulideni,zheijiuxuyaokanyixiadailileideyuanmale。danshidailileishichengxudongtaishengchengzijiemajiazaide,

zenmekanyuanmani?

meiguanxi,keyizaimainfangfazhongjiarusystem.getproperties().put(“sun.misc.proxygenerator.savegeneratedfiles”,”true”),zheiyangjiuhuibashengchengdedailileiclasswenjianbaocunzaibendicipanshang,ranhouzaifanbianyikeyidedaodailileideyuanma:

607的彩的正确网址package common;import java.lang.reflect.invocationhandler;import java.lang.reflect.method;import java.lang.reflect.proxy;import java.lang.reflect.undeclaredthrowableexception;public final class $proxy0 extends proxyimplements test.subject{private static method m4;private static method m1;private static method m3;private static method m0;private static method m2;static{try {m4 = class.forname("test$subject").getmethod("sayhello", new class[0]);m1 = class.forname("java.lang.object").getmethod("equals", new class[] { class.forname("java.lang.object") });m3 = class.forname("test$subject").getmethod("sayhi", new class[0]);m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]);m2 = class.forname("java.lang.object").getmethod("tostring", new class[0]);} catch (exception e) {throw new runtimeexception(e);}}public $proxy0(invocationhandler paraminvocationhandler){super(paraminvocationhandler);}public final void sayhello(){try{this.h.invoke(this, m4, null);return;}catch (runtimeexception localruntimeexception){throw localruntimeexception;}catch (throwable localthrowable){throw new undeclaredthrowableexception(localthrowable);}}public final boolean equals(object paramobject){try{return ((boolean)this.h.invoke(this, m1, new object[] { paramobject })).booleanvalue();}catch (runtimeexception localruntimeexception){throw localruntimeexception;}catch (throwable localthrowable){throw new undeclaredthrowableexception(localthrowable);}}public final void sayhi(){try{this.h.invoke(this, m3, null);return;}catch (runtimeexception localruntimeexception){throw localruntimeexception;}catch (throwable localthrowable){throw new undeclaredthrowableexception(localthrowable);}}public final int hashcode(){try{return ((integer)this.h.invoke(this, m0, null)).intvalue();}catch (runtimeexception localruntimeexception){throw localruntimeexception;}catch (throwable localthrowable){throw new undeclaredthrowableexception(localthrowable);}}public final string tostring(){try{return (string)this.h.invoke(this, m2, null);}catch (runtimeexception localruntimeexception){throw localruntimeexception;}catch (throwable localthrowable){throw new undeclaredthrowableexception(localthrowable);}}}

womenkeyikandaodailileineibushixianbijiaojiandan,zaidiaoyongmeigedailileimeigefangfadeshihou,douyongfanshequdiaohdeinvokefangfa(yejiushiwomenzidingyideinvocationhandlerdezileizhongzhongxiedeinvokefangfa),yongcanshuchuandiledailileishili、jiekoufangfa、diaoyongcanshuliebiao,zheiyangwomenzaizhongxiedeinvokefangfazhongjiukeyishixianduisuoyoufangfadetongyibaozhuangle。

总结

dongtaidailixiangduiyujingtaidailizaishiyongshangdeyoudianzhuyaoshinenggouduiyigeduixiangdesuoyoufangfajinxingtongyibaozhuang,erqiehouqibeidailideleitianjiafangfadeshihoudongtaidailileibuxuyaogaidong。

quedianshiyaoqiubeidailideleibixushixianlejiekou,yinweidongtaidailileizaishixiandeshihoujichengleproxylei,javabuzhichiduojicheng,yincidongtaidailileizhinenggenjujiekoulaidingyifangfa。

607的彩的正确网址zuihoudongtaidailizhisuoyijiaozuodongtaidailishiyinweijavazaishixiandongtaidailideshihou,dongtaidailileishizaiyunxingshidongtaishengchenghejiazaide,xiangduide,jingtaidailileiheqitaputongleiyixia,zaileijiazaijieduanjiujiazaile。

yishangjiushibenwendequanbuneirong,xiwangduidajiadexuexiyousuobangzhu,yexiwangdajiaduoduozhichiwomen。

benwenbiaoti: shenruxuexijava dongtaidaili

yishangjiushangyouguanshenruxuexijavadongtaidailidequanbuneirong,xuebuyuanquanmianjieshaobianchengjishu、caozuoxitong、shujuku、webqianduanjishudengneirong。

baoqian!pinglunyiguanbi.

2元中国福利彩票怎么看 2元买彩票选几个数字 2元中国福利彩票的买法 2元就可以打1毛的斗地主棋牌 2元彩是值得您信赖的 2元斗地主群 2元的彩的网 2元彩票双色球走势图双色球 2元彩票网全国走势图 2元就可以打1毛的炸金花棋牌