java反射拼接方法名动态执行方法

近期由于负责项目的一个模块,该模块下有很多分类,每个分类都有一个编码code,这个值是作为一个参数携带过来的.但是每个code确实对应一个方法的.

code的值有很多个,自己又不想做ifelse或者switch判断于是就狂搜资料,主要让我发现利用java的反射机制可以完美的解决这个问题

测试代码如下:(可以携带多个参数哦)

package com.escs.xmlutils;

import java.lang.reflect.Method;

public class Test {

    public String ceshi(){
        System.out.println("1111111111111");
        return "success";
    }
     public static void main(String[] args) throws Exception { 
             //里面写自己的类名及路径
            Class<?> c = Class.forName("com.escs.xmlutils.Test");
            Object obj = c.newInstance();
            //第一个参数写的是方法名,第二个第三个...写的是方法参数列表中参数的类型
            Method method=c.getMethod("ceshi2", String.class,int.class);
            //invoke是执行该方法,并携带参数值
            String str2= (String) method.invoke(obj, new Object[]{"myname",4});
           System.out.println(str2);
         }      
     public  String ceshi(String str){
         //for(int j=0;j<Integer.valueOf(i);j++){
             System.out.println(str);
         //}
        
         return str;
     }
         
     public  String ceshi2(String str,int i){
         for(int j=0;j<i;j++){
             System.out.println(str+"22222");
         }
        
         return str;
     }
       
    }   

这样要是动态拼接方法名就更简单了.比如,我的code值有100个,分别为1~100,我code方法分别为ReturnCodeList();这个时候我们把上面的方法抽取出来,返回我们需要的值就行了比如:

 public String fanShe(String methodName,String className) throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        //里面写自己的类名及路径
            Class<?> c = Class.forName(className);
            Object obj = c.newInstance();
            //第一个参数写的是方法名,第二个第三个...写的是方法参数列表中参数的类型
            Method method=c.getMethod(methodName, String.class,int.class);
            //invoke是执行该方法,并携带参数值
            String str2= (String) method.invoke(obj, new Object[]{"myname",4});
            return str2;
     }

当然在实际的需求中还是要根据项目的需要来自己抽取方法的.希望对大家有帮助.

想更深入了解java反射原理的可以参考:http://www.cnblogs.com/forlina/archive/2011/06/21/2085849.html

原文地址:https://www.cnblogs.com/LT0314/p/3723762.html