分享

java根据方法名动态调用方法

 quasiceo 2015-01-17

java根据方法名动态调用方法

(2013-03-08 17:10:26)

分类: JAVA技术
1.Action action=new Action();//类例化一个对象
Method method = action.getClass().getMethod(methodName, Class<?>... parameterTypes);
method  .invoke( action ,Object... args); 
parameterTypes :方法传入参数的类型 可指定一个,也可以指定多个,但一定要一一对应
args:传入的参数 可指定一个,也可以指定多个,但要与parameterTypes 类型对应
2.
   Class[] cargs = new Class[1];
            String realArgs = userId;
            cargs[0] = realArgs.getClass();
            Method method = this.getClass().getMethod(methodStr,cargs);
            Object arglist[] = new Object[1];
            arglist[0] = userId;
            method.invoke(this, arglist);
2)new当前类(这个是借鉴,不过这个可以直接看结果哦)

import java.lang.reflect.Method;

public class testM {

 public static void main(String[] args) {

  try {

   testM new testM();
   Class t.getClass();
   Class[] cargs new Class[2];
   String[] realArgs "aa", "bb" };
   cargs[0] realArgs.getClass();
   Integer in new Integer(2);
   cargs[1] in.getClass();
   Method c.getMethod("test", cargs); // 调用了test方法,返回值为Method变量
   Object[] inArgs new Object[2];
   inArgs[0] realArgs;
   inArgs[1] in;
   m.invoke(t, inArgs);

  catch (Exception e) {
   System.out.println(e);
  }

 }

 public void test(String[] str, Integer stri) {

  for (int 0; str.length; j++)
   System.out.println(str[j]);
  System.out.println(stri.intValue());

 }

}

3.项目中写到的:


if(action.startsWith("dispatch")){
dipatchMethodName = mainDispatch.filter(action);
System.out.println("===========dipatchMethodName:"+dipatchMethodName);
parameterTypes[0]=HttpServletRequest.class;
parameterTypes[1]=HttpServletResponse.class;
Method method = businessAction.getClass().getMethod(dipatchMethodName, parameterTypes);
forward = (Boolean) method.invoke(businessAction, req,resp);
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多