通过反射实现Java下的委托机制代码详解
简述
一直对Java没有现成的委托机制耿耿于怀,所幸最近有点时间,用反射写了一个简单的委托模块,以供参考。
模块API
publicClassDelegater()//空参构造,该类管理委托实例并实现委托方法 //添加一个静态方法委托,返回整型值ID代表该方法与参数构成的实例。若失败,则返回-1。 publicsynchronizedintaddFunctionDelegate(Class>srcClass,StringmethodName,Object...params); //添加一个实例方法委托,返回整型值ID代表该方法与参数构成的实例。若失败,则返回-1。 publicsynchronizedintaddFunctionDelegate(ObjectsrcObj,StringmethodName,Object...params); //根据整型ID从委托实例中删除一个方法委托,返回是否成功 publicsynchronizedBooleanremoveMethod(intregisterID); //依次执行该委托实例中的所有方法委托(无序) publicsynchronizedvoidinvokeAllMethod(); //将参数表转换为参数类型表 privateClass>[]getParamTypes(Object[]params); //由指定的Class、方法名、参数类型表获得方法实例 privateMethodgetDstMethod(Class>srcClass,StringmethodName,Class>[]paramTypes); classDelegateNode(MethodrefMethod,Object[]params)//DelegateNode类在不使用Object构造时叙述了一个静态方法委托,包括方法实例及参数表 classDelegateNode(ObjectsrcObj,MethodrefMethod,Object[]params)//DelegateNode类在使用Object构造时叙述了一个实例方法委托,包括类实例、方法实例及参数表 publicvoidinvokeMethod(); //执行该节点叙述的方法委托
源代码
importjava.lang.reflect.InvocationTargetException; importjava.lang.reflect.Method; importjava.util.Hashtable; /**Delegater类使用RTTI及反射实现Java下的委托机制 *@author三向板砖 **/ publicclassDelegater{ staticintregister=Integer.MIN_VALUE; //ID分配变量 HashtablenodeTable; //管理ID与对应委托的容器 publicDelegater() { nodeTable=newHashtable (); } //添加静态方法委托 publicsynchronizedintaddFunctionDelegate(Class>srcClass,StringmethodName,Object...params) { Class>[]paramTypes=getParamTypes(params); MethodrefMethod; if((refMethod=getDstMethod(srcClass,methodName,paramTypes))!=null) { register++; nodeTable.put(register,newDelegateNode(refMethod,params)); returnregister; }else { return-1; } } //添加动态方法委托 publicsynchronizedintaddFunctionDelegate(ObjectsrcObj,StringmethodName,Object...params) { Class>[]paramTypes=getParamTypes(params); MethodrefMethod; if((refMethod=getDstMethod(srcObj.getClass(),methodName,paramTypes))!=null) { register++; nodeTable.put(register,newDelegateNode(srcObj,refMethod,params)); returnregister; }else { return-1; } } //删除一个方法委托 publicsynchronizedBooleanremoveMethod(intregisterID) { if(nodeTable.containsKey(registerID)) { nodeTable.remove(registerID); returntrue; } returnfalse; } //无序地执行委托方法 publicsynchronizedvoidinvokeAllMethod() { for(DelegateNodenode:nodeTable.values()) { node.invokeMethod(); } } //将参数表转化为参数类型表 privateClass>[]getParamTypes(Object[]params) { Class>[]paramTypes=newClass>[params.length]; for(inti=0;i srcClass,StringmethodName,Class>[]paramTypes) { Methodresult=null; try{ result=srcClass.getMethod(methodName,paramTypes); if(result.getReturnType()!=void.class) { System.out.println("Warning,Method:"+methodName+"hasareturnvalue!"); } } catch(NoSuchMethodException|SecurityExceptione){ System.out.println("CanNotFoundMethod:"+methodName+",ensureit'sexistandvisible!"); } returnresult; } } classDelegateNode { ObjectsrcObj; MethodrefMethod; Object[]params; publicDelegateNode(MethodrefMethod,Object[]params) { this.refMethod=refMethod; this.params=params; } publicDelegateNode(ObjectsrcObj,MethodrefMethod,Object[]params) { this.srcObj=srcObj; this.refMethod=refMethod; this.params=params; } publicvoidinvokeMethod() { try{ refMethod.invoke(srcObj,params); } catch(IllegalAccessException|IllegalArgumentException |InvocationTargetExceptione){ System.out.println("Method:"+refMethod.toString()+"invokefail!"); } } }
模块测试
publicclassDelegaterTest{ publicvoidshowInfo() { System.out.println("HelloDelegate!"); } publicvoidshowCustomInfo(Stringinfo) { System.out.println(info); } publicstaticvoidshowStaticInfo() { System.out.println("StaticDelegate!"); } publicstaticvoidshowCustomStaticInfo(Stringinfo) { System.out.println(info); } publicstaticvoidmain(String[]args){ Delegaterdele=newDelegater(); DelegaterTesttester=newDelegaterTest(); intID=dele.addFunctionDelegate(tester,"showInfo"); dele.addFunctionDelegate(tester,"showCustomInfo","Custom!"); dele.addFunctionDelegate(DelegaterTest.class,"showStaticInfo"); dele.addFunctionDelegate(DelegaterTest.class,"showCustomStaticInfo","StaticCustom!"); dele.invokeAllMethod(); dele.removeMethod(ID); System.out.println("------------------"); dele.invokeAllMethod(); } }
执行结果:
StaticCustom!
StaticDelegate!
Custom!
HelloDelegate!
------------------
StaticCustom!
StaticDelegate!
Custom!
其他事项
一些public方法使用synchronized是为了保证register变量的线程安全,使其不会因为多线程而出错。
对于有返回值的委托,会报出警告,但模块还是接受这样的委托的,不过在执行委托时您将不能得到返回值。
添加的委托最大值是Integer.MAX_VALUE-Integer.MIN_VALUE超出后的容错处理没有考虑(一般也没这么多函数需要委托的吧。
委托执行是无序的,而且,需要性能要求时,委托的函数尽量不要有阻塞过程,否则会影响其他委托函数的执行。
还有什么问题可以发上来一同探讨。
总结
以上就是本文关于通过反射实现Java下的委托机制代码详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他Java相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。