0

I want to make the method name in the class dynamic when I create a object from the class I want to execute the method name dynamically bellow is my code .

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 .
            } 
Sheridan
  • 68,826
  • 24
  • 143
  • 183

2 Answers2

1

i want to execute the method name dynamically

Use Reflections in Java to achieve this.

Sample code:

        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;
            }
        }

OR simply try this:

       // Get the method name at runtime
        Method method = ClassName.class.getMethod(N.getTCName(), null);
        method.invoke(new ClassName(), null);
Community
  • 1
  • 1
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

Use java reflection.

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

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

getReportName is an example of the method name you want to call. Please refer to java reflection.

Chamil
  • 805
  • 5
  • 12