Java Proxy机制详细解读
动态代理其实就是java.lang.reflect.Proxy类动态的根据您指定的所有接口生成一个classbyte,该class会继承Proxy类,并实现所有你指定的接口(您在参数中传入的接口数组);然后再利用您指定的classloader将classbyte加载进系统,最后生成这样一个类的对象,并初始化该对象的一些值,如invocationHandler,以即所有的接口对应的Method成员。初始化之后将对象返回给调用的客户端。这样客户端拿到的就是一个实现你所有的接口的Proxy对象。请看实例分析:
一 业务接口类
publicinterfaceBusinessProcessor{ publicvoidprocessBusiness(); }
二业务实现类
publicclassBusinessProcessorImplimplementsBusinessProcessor{ publicvoidprocessBusiness(){ System.out.println("processingbusiness....."); } }
三业务代理类
importjava.lang.reflect.InvocationHandler; importjava.lang.reflect.Method; publicclassBusinessProcessorHandlerimplementsInvocationHandler{ privateObjecttarget=null; BusinessProcessorHandler(Objecttarget){ this.target=target; } publicObjectinvoke(Objectproxy,Methodmethod,Object[]args) throwsThrowable{ System.out.println("Youcandosomethingherebeforeprocessyourbusiness"); Objectresult=method.invoke(target,args); System.out.println("Youcandosomethinghereafterprocessyourbusiness"); returnresult; } }
四客户端应用类
importjava.lang.reflect.Field; importjava.lang.reflect.Method; importjava.lang.reflect.Modifier; importjava.lang.reflect.Proxy; publicclassTest{ publicstaticvoidmain(String[]args){ BusinessProcessorImplbpimpl=newBusinessProcessorImpl(); BusinessProcessorHandlerhandler=newBusinessProcessorHandler(bpimpl); BusinessProcessorbp=(BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(),bpimpl.getClass().getInterfaces(),handler); bp.processBusiness(); } }
现在我们看一下打印结果:
Youcandosomethingherebeforeprocessyourbusiness processingbusiness..... Youcandosomethinghereafterprocessyourbusiness
通过结果我们就能够很简单的看出Proxy的作用了,它能够在你的核心业务方法前后做一些你所想做的辅助工作,如log日志,安全机制等等。
现在我们来分析一下上面的类的工作原理。
类一二没什么好说的。先看看类三吧。实现了InvocationHandler接口的invoke方法。其实这个类就是最终Proxy调用的固定接口方法。Proxy不管客户端的业务方法是怎么实现的。当客户端调用Proxy时,它只会调用InvocationHandler的invoke接口,所以我们的真正实现的方法就必须在invoke方法中去调用。关系如下:
BusinessProcessorImplbpimpl=newBusinessProcessorImpl(); BusinessProcessorHandlerhandler=newBusinessProcessorHandler(bpimpl); BusinessProcessorbp=(BusinessProcessor)Proxy.newProxyInstance(....); bp.processBusiness()-->invocationHandler.invoke()-->bpimpl.processBusiness();
那么bp到底是怎么样一个对象呢。我们改一下main方法看一下就知道了:
publicstaticvoidmain(String[]args){ BusinessProcessorImplbpimpl=newBusinessProcessorImpl(); BusinessProcessorHandlerhandler=newBusinessProcessorHandler(bpimpl); BusinessProcessorbp=(BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(),bpimpl.getClass().getInterfaces(),handler); bp.processBusiness(); System.out.println(bp.getClass().getName()); }
输出结果:
Youcandosomethingherebeforeprocessyourbusiness processingbusiness..... Youcandosomethinghereafterprocessyourbusiness $Proxy0
bp原来是个$Proxy0这个类的对象。那么这个类到底是长什么样子呢?好的。我们再写二个方法去把这个类打印出来看个究竟,是什么三头六臂呢?我们在main下面写如下两个静态方法。
publicstaticStringgetModifier(intmodifier){ Stringresult=""; switch(modifier){ caseModifier.PRIVATE: result="private"; caseModifier.PUBLIC: result="public"; caseModifier.PROTECTED: result="protected"; caseModifier.ABSTRACT: result="abstract"; caseModifier.FINAL: result="final"; caseModifier.NATIVE: result="native"; caseModifier.STATIC: result="static"; caseModifier.SYNCHRONIZED: result="synchronized"; caseModifier.STRICT: result="strict"; caseModifier.TRANSIENT: result="transient"; caseModifier.VOLATILE: result="volatile"; caseModifier.INTERFACE: result="interface"; } returnresult; } publicstaticvoidprintClassDefinition(Classclz){ StringclzModifier=getModifier(clz.getModifiers()); if(clzModifier!=null&&!clzModifier.equals("")){ clzModifier=clzModifier+""; } StringsuperClz=clz.getSuperclass().getName(); if(superClz!=null&&!superClz.equals("")){ superClz="extends"+superClz; } Class[]interfaces=clz.getInterfaces(); Stringinters=""; for(inti=0;i再改写main方法
publicstaticvoidmain(String[]args){ BusinessProcessorImplbpimpl=newBusinessProcessorImpl(); BusinessProcessorHandlerhandler=newBusinessProcessorHandler(bpimpl); BusinessProcessorbp=(BusinessProcessor)Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(),bpimpl.getClass().getInterfaces(),handler); bp.processBusiness(); System.out.println(bp.getClass().getName()); Classclz=bp.getClass(); printClassDefinition(clz); }现在我们再看看输出结果:
Youcandosomethingherebeforeprocessyourbusiness processingbusiness..... Youcandosomethinghereafterprocessyourbusiness $Proxy0 $Proxy0extendsjava.lang.reflect.Proxyimplementscom.tom.proxy.dynamic.BusinessProcessor { java.lang.reflect.Methodm4; java.lang.reflect.Methodm2; java.lang.reflect.Methodm0; java.lang.reflect.Methodm3; java.lang.reflect.Methodm1; voidprocessBusiness(); inthashCode(); booleanequals(java.lang.Object); java.lang.StringtoString(); }很明显,Proxy.newProxyInstance方法会做如下几件事:
1,根据传入的第二个参数interfaces动态生成一个类,实现interfaces中的接口,该例中即BusinessProcessor接口的processBusiness方法。并且继承了Proxy类,重写了hashcode,toString,equals等三个方法。具体实现可参看ProxyGenerator.generateProxyClass(...);该例中生成了$Proxy0类
2,通过传入的第一个参数classloder将刚生成的类加载到jvm中。即将$Proxy0类load
3,利用第三个参数,调用$Proxy0的$Proxy0(InvocationHandler)构造函数创建$Proxy0的对象,并且用interfaces参数遍历其所有接口的方法,并生成Method对象初始化对象的几个Method成员变量
4,将$Proxy0的实例返回给客户端。
现在好了。我们再看客户端怎么调就清楚了。
1,客户端拿到的是$Proxy0的实例对象,由于$Proxy0继承了BusinessProcessor,因此转化为BusinessProcessor没任何问题。
BusinessProcessorbp=(BusinessProcessor)Proxy.newProxyInstance(....);2,bp.processBusiness();
实际上调用的是$Proxy0.processBusiness();那么$Proxy0.processBusiness()的实现就是通过InvocationHandler去调用invoke方法啦!
总结
以上就是本文关于JavaProxy机制详细解读的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:详解java中的互斥锁信号量和多线程等待机制、关于Java反射机制你需要知道的事情、Java的RTTI和反射机制代码分析等,有什么问题可以随时留言,小编会及时回复大家。