- //一個在java運行時利用反射動態調用方法的例子
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class LoadMethod {
- public Object Load(String cName,String MethodName,String[] type,String[] param){
- Object retobj = null;
- try {
- //加載指定的Java類
- Class cls = Class.forName(cName);
- //獲取指定對象的實例
- Constructor ct = cls.getConstructor(null);
- Object obj = ct.newInstance(null);
- //構建方法參數的數據類型
- Class partypes[] = this.getMethodClass(type);
- //在指定類中獲取指定的方法
- Method meth = cls.getMethod(MethodName, partypes);
- //構建方法的參數值
- Object arglist[] = this.getMethodObject(type,param);
- //調用指定的方法並獲取返回值爲Object類型
- retobj= meth.invoke(obj, arglist);
- }
- catch (Throwable e) {
- System.err.println(e);
- }
- return retobj;
- }
- //獲取參數類型Class[]的方法
- public Class[] getMethodClass(String[] type){
- Class[] cs = new Class[type.length];
- for (int i = 0; i < cs.length; i++) {
- if(!type[i].trim().equals("")||type[i]!=null){
- if(type[i].equals("int")||type[i].equals("Integer")){
- cs[i]=Integer.TYPE;
- }else if(type[i].equals("float")||type[i].equals("Float")){
- cs[i]=Float.TYPE;
- }else if(type[i].equals("double")||type[i].equals("Double")){
- cs[i]=Double.TYPE;
- }else if(type[i].equals("boolean")||type[i].equals("Boolean")){
- cs[i]=Boolean.TYPE;
- }else{
- cs[i]=String.class;
- }
- }
- }
- return cs;
- }
- //獲取參數Object[]的方法
- public Object[] getMethodObject(String[] type,String[] param){
- Object[] obj = new Object[param.length];
- for (int i = 0; i < obj.length; i++) {
- if(!param[i].trim().equals("")||param[i]!=null){
- if(type[i].equals("int")||type[i].equals("Integer")){
- obj[i]= new Integer(param[i]);
- }else if(type[i].equals("float")||type[i].equals("Float")){
- obj[i]= new Float(param[i]);
- }else if(type[i].equals("double")||type[i].equals("Double")){
- obj[i]= new Double(param[i]);
- }else if(type[i].equals("boolean")||type[i].equals("Boolean")){
- obj[i]=new Boolean(param[i]);
- }else{
- obj[i] = param[i];
- }
- }
- }
- return obj;
- }
- }
一個在java運行時利用反射動態調用方法的例子
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.