代码中使用的字符串输入?

时间:2015-12-02 01:58:35

标签: java string

所以我想做的是让一个类让我选择另一个类来运行。我目前通过用户输入与预定数组中的字符串匹配的字符串来设置此设置。有错误的部分是item runThis = new item();,我完全可以预料会失败,但有没有办法解决我失败的问题?

class Class1 {
    public static void main(String[] args){
        String[] options = new String[] {"Class2", "Class3", "Class4", "STOP"};
        String response = "";
        Scanner input = new Scanner(System.in);

        while (!response.equals("STOP")){
            System.out.println("Which program would you like to run?\nYour options are:");

            for (String item : options) {
                System.out.println(item);
            }

            response=input.nextLine();
            for (String item : options) {
                if(resonse.equals(item))
                item runThis = new item();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

要从字符串变量动态执行类,可以使用:

Class c = Class.forName("className");
c.newInstance();

在你的情况下,它将是:

for (String item : options){
    if(response.equals(item)){
        Class c;
        try {
            c = Class.forName(response);
            c.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

答案 1 :(得分:1)

这是一种方法完全类型安全,假设您的类是Runnable

    final List<Class<? extends Runnable>> programs = Arrays.asList(
            Class2.class, Class3.class, Class4.class);

    Scanner input = new Scanner(System.in);
    for (;;) {
        System.out.println("Which program would you like to run?\n" +
                           "Your options are:");
        for (Class<? extends Runnable> program : programs)
            System.out.println("  " + program.getSimpleName());
        System.out.println("  STOP");
        String response = input.nextLine();
        if (response.equals("STOP"))
            break;
        Class<? extends Runnable> programToRun = null;
        for (Class<? extends Runnable> program : programs)
            if (response.equals(program.getSimpleName())) {
                programToRun = program;
                break;
            }
        if (programToRun == null)
            System.out.println("Invalid program. Try again.");
        else
            try {
                programToRun.newInstance().run();
            } catch (Throwable e) {
                e.printStackTrace(System.out);
            }
    }