首页 > 解决方案 > 调用名称在字符串中的类

问题描述

我正在尝试调用一个类,其名称的一部分包含在通过读取控制台输入获得的字符串中。

static void menu() {

        System.out.println("Choose a menu:");
        System.out.print("\n");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String nome = null;
        try {
            nome = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.print("\n");
        System.out.println("Opening: " + nome);
        System.out.print("\n");

        String funzione = nome + ".funzione();";

        try {
            Runtime.getRuntime().exec(funzione);
        } catch (IOException e) {
            System.out.println(funzione);
            e.printStackTrace();
        }

基本上,如果我写“打印”,我想执行print.function();稍后在程序中调用的。该代码有效,但它也输出错误java.io.IOException: Cannot run program "print.function();": error=2, No such file or directory,但print.function();无论如何都会执行。

需要明确的是,我是故意遵循这种方法而不是 switch case。

我认为我以错误的方式执行该过程,有人可以在哪里突出显示我吗?非常感谢。

标签: java

解决方案


推荐阅读