随笔 - 40, 文章 - 0, 评论 - 20, 引用 - 0
数据加载中……

执行过程中动态执行方法

在编程中可能回碰到一些到实际运行时才指定要调用的方法的需要,最典型的是Struct的DispatchAction类,
它能根据用户页面请求参数的不同来调用不同的方法来处理用户请求。我下面写了一个简单的例子来简单演示其
实现方法:

package learn;
import java.lang.NoSuchMethodException;
import java.lang.reflect.Method;
import java.util.Date;

public class TestMethod{
    protected Class clazz = this.getClass();
    protected Class[] no_parameter = {};  //方法无参数
    protected Class[] string_parameter = {String.class}; //以String 为参数
    protected Class[] int_parameter = {int.class};  //以int为参数
    protected Class[] multi_parameter = {String.class,Date.class}; //多个参数,第一个为String,第二二个为Date   
   
    public void method1(){
      System.out.println("method1");
    }
   
    public void method2(String str){
      System.out.println("method2=>"+str);
    }
   
    public void method3(int i){
      System.out.println("method2=>"+i);
    }
   
    public void method4(String str,Date date){
      System.out.println("method4=>"+str+"==="+date.toLocaleString());
    }
   
    public void execute(String methodName,int type,java.util.List list) throws Exception{
      try {
        Method  m = getMethod(methodName,type);
        int size = (list != null )? list.size():0;
        Object o [] = new Object[size];
        for( int i =0 ; i< size ; i++ )
          o[i] = list.get(i);  //准备参数
        m.invoke(this,o);
      }
      catch (Exception ex) {
        ex.printStackTrace();
        throw new Exception(ex.getMessage());
      }
    }
   
    private Method getMethod(String name,int type)throws NoSuchMethodException{
        Method m = null;
        switch(type){
          case 1:
            m = clazz.getMethod(name,no_parameter);
            break;
          case 2:
            m = clazz.getMethod(name,string_parameter);
            break;
          case 3:
            m = clazz.getMethod(name,int_parameter);
            break;
          case 4:
            m = clazz.getMethod(name,multi_parameter);
            break;
          default:
            m = clazz.getMethod(name,no_parameter);
        }
        return m;
    }
   
    public static void main(String [] argv){
      TestMethod testMethod = new TestMethod();
      try{
        java.util.List list = new java.util.ArrayList();
        testMethod.execute("method1", 1, list);
        list.add("
http://www.blogjava.net/minmoon");
        testMethod.execute("method2", 2, list);
        list.clear();
        list.add("
mailTo:xiaoliang@aspire-tech.com");
        list.add(new Date());
        testMethod.execute("method4",4,list);
      }
      catch(Exception e){
        e.printStackTrace();
      }
    }
}

其中几个关键的地方说明一下:
  clazz.getMethod(name,multi_parameter);  其中multi_parameter是要根据实际方法的参数来定义的。
  m.invoke(this,o);   o是要传入方法的参数列表。

posted on 2005-11-23 00:18 月亮 阅读(480) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: