Search code examples
javainvoke

Java invoke class to call method inside


I have a problem. In my code I have the following line:

HashMap<String, String> strategyResponse = strategy_005.run(runDateTimeLocal);

This function is inside the strategy_005 class:

public class strategy_005 {

    public static HashMap<String, String> run(Integer i) {

        HashMap<String, String> output = new HashMap<>();
        output.put("Response", i.toString());
        return output;

    }

}

I am not calling the function in the strategy_005 class, but in my MainClass. The problem I have is that the 005 part in the class is dynamic, so I have multiple classes from strategy_001 to strategy_015.

Here is the code from my MainClass:

public class MainClass {

    public static void main(String[] args) {

        for (int i = 1; i <= 15; i++) {
            
            // Call every "strategy_0(i)" run() method
            HashMap<String, String> strategyResponse = strategy_005.run(i);
            System.out.println(strategyResponse.get("Response"));

        }

    }

}

I know how to invoke methods from a class by name, but I don't know how to invoke a class and then call the method that I do know. The only thing I found that is close to what I want is this: Creating an instance using the class name and calling constructor

Unfortunatly this topic is about calling the constructor, but I want to call a custom method. Please let me know how I can achieve this!


Solution

  • you can invoke methods using reflection:

    public HashMap<String, String> invoke(int i, int arg0){
        Class<?> clz = Class.forName("package_name.strategy_" + i);
        Method method = clz.getDeclaredMethod("run", int.class);
        return (HashMap<String, String>) method.invoke(null, arg0);
    }
    
    for(int i = 0; i < 15; i++){
        HashMap<String, String> output = invoke(i, runDateTimeLocal);
    }
    

    the name of class for Class.forName("package_name.strategy_" + i); must be fully quallified with package name