1

So what I want to do is have a class that lets me choose another class to run. I currently have this set up by the user typing in a string that matches a string in a predetermined array. The part with an error is item runThis = new item(); which I fully expected to fail, but is there a way to do that which I am failing?

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 Answers 2

1

To execute classes dynamically from string variables, you can use:

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

In your case, it would be:

for (String item : options){
    if(response.equals(item)){
        Class c;
        try {
            c = Class.forName(response);
            c.newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

on c.newInstance(); I get these two errors: unreported exception java.lang.InstantiationException; must be caught or declared to be thrown and variable c might not have been initialized
Yea I think you didn't do the ExceptionHandling. Try my edited answer.
with that, the first error only shows on c.newInstance(); instead of both lines.
lol ok, exceptions handled. Try again, and this time, it will work. Sorry about troubles.
That fixed it, Thank you!
1

Here is a way to do it fully type-safe, assuming your classes are 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);
            }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.