一个在java运行时利用反射动态调用方法的例子

  1. //一个在java运行时利用反射动态调用方法的例子
  2. import java.lang.reflect.Constructor;  
  3. import java.lang.reflect.Method;  
  4.   
  5. public class LoadMethod {  
  6. public Object Load(String cName,String MethodName,String[] type,String[] param){  
  7. Object retobj = null;  
  8. try {  
  9. //加载指定的Java类  
  10. Class cls = Class.forName(cName);  
  11.   
  12. //获取指定对象的实例  
  13. Constructor ct = cls.getConstructor(null);  
  14. Object obj = ct.newInstance(null);  
  15.   
  16. //构建方法参数的数据类型  
  17. Class partypes[] = this.getMethodClass(type);  
  18.   
  19. //在指定类中获取指定的方法  
  20. Method meth = cls.getMethod(MethodName, partypes);  
  21.   
  22. //构建方法的参数值  
  23. Object arglist[] = this.getMethodObject(type,param);  
  24.   
  25. //调用指定的方法并获取返回值为Object类型  
  26. retobj= meth.invoke(obj, arglist);  
  27.   
  28. }  
  29. catch (Throwable e) {  
  30. System.err.println(e);  
  31. }  
  32. return retobj;  
  33. }  
  34.   
  35. //获取参数类型Class[]的方法  
  36. public Class[] getMethodClass(String[] type){  
  37. Class[] cs = new Class[type.length];  
  38. for (int i = 0; i < cs.length; i++) {  
  39. if(!type[i].trim().equals("")||type[i]!=null){  
  40. if(type[i].equals("int")||type[i].equals("Integer")){  
  41. cs[i]=Integer.TYPE;  
  42. }else if(type[i].equals("float")||type[i].equals("Float")){  
  43. cs[i]=Float.TYPE;  
  44. }else if(type[i].equals("double")||type[i].equals("Double")){  
  45. cs[i]=Double.TYPE;  
  46. }else if(type[i].equals("boolean")||type[i].equals("Boolean")){  
  47. cs[i]=Boolean.TYPE;  
  48. }else{  
  49. cs[i]=String.class;  
  50. }  
  51. }  
  52. }  
  53. return cs;  
  54. }  
  55.   
  56. //获取参数Object[]的方法  
  57. public Object[] getMethodObject(String[] type,String[] param){  
  58. Object[] obj = new Object[param.length];  
  59. for (int i = 0; i < obj.length; i++) {  
  60. if(!param[i].trim().equals("")||param[i]!=null){  
  61. if(type[i].equals("int")||type[i].equals("Integer")){  
  62. obj[i]= new Integer(param[i]);  
  63. }else if(type[i].equals("float")||type[i].equals("Float")){  
  64. obj[i]= new Float(param[i]);  
  65. }else if(type[i].equals("double")||type[i].equals("Double")){  
  66. obj[i]= new Double(param[i]);  
  67. }else if(type[i].equals("boolean")||type[i].equals("Boolean")){  
  68. obj[i]=new Boolean(param[i]);  
  69. }else{  
  70. obj[i] = param[i];  
  71. }  
  72. }  
  73. }  
  74. return obj;  
  75. }  
  76. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值