如何在类动态中使方法名称?

时间:2014-03-03 09:47:59

标签: java eclipse

当我从类中创建一个对象时,我希望在类动态中创建方法名称我想要动态地执行方法名称是我的代码。

public static void ExecuteTest() throws Exception 
{
    for (int i = 1,  j = 1;  i < 2;  i = i+1, j = j+1)  {    
            FW_ReadExcelFile N = new FW_ReadExcelFile();
            FW_ReadExcelFile.setExcelSheetEnvValues(i,i);
             //java.lang.String Flag2 = N.getTCExecuteFlag() ;

             String Flag = "YES";
             String Flag21 = N.getTCExecuteFlag();


            if ( Flag.equals(Flag21)  ){
                String TCName = N.getTCName();
                FW_Report u = new FW_Report();
                u.TCName; // the FW_Report  class has many methods and I want to call the method on my demand .
            } 

2 个答案:

答案 0 :(得分:1)

  

我想动态执行方法名称

使用Reflections in Java来实现这一目标。

示例代码:

        Class<?> name = Class.forName("ClassName");
        Object instance = name.newInstance();
        Method[] methods = name.getMethods();

        for (Method method : methods) {
            if (method.getName().equals(N.getTCName())) {
                // Match found. Invoke the method. call the method on my demand.
                method.invoke(instance, null);
                break;
            }
        }

或者只是试试这个:

       // Get the method name at runtime
        Method method = ClassName.class.getMethod(N.getTCName(), null);
        method.invoke(new ClassName(), null);

答案 1 :(得分:0)

使用java反射。

java.lang.reflect.Method method = u.getClass().getMethod("getReportName", param1.class, param2.class, ..);

method.invoke(obj,/*param1*/,/*param2*/,....);

getReportName是您要调用的方法名称的示例。请参考java反射。