一個在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. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章