Java调用类来调用里面的方法

A.弗里斯维克

我有问题。在我的代码中,我有以下几行:

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

这个函数在strategy_005类中:

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;

    }

}

我不是在strategy_005课堂上调用函数,而是在我的MainClass. 我的问题是类中的005部分是动态的,所以我有多个类从strategy_001strategy_015.

这是我的代码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"));

        }

    }

}

我知道如何按名称调用类中的方法,但我不知道如何调用类,然后调用我知道的方法。我发现唯一接近我想要的是:使用类名创建一个实例并调用构造函数

不幸的是,本主题是关于调用构造函数,但我想调用自定义方法。请让我知道我如何实现这一目标!

用户3840019

您可以使用反射调用方法

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

类的名称Class.forName("package_name.strategy_" + i);必须与包名称完全限定

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章