Search code examples
javaarraysclassprogram-entry-point

Call a class from another class without having to change the class type (or the return) Java


I am trying to run a class from another class. But it asks me to change the type when I store the class name in an array. I want the user to enter a number which would be fed into the array and run the class at that array value. Here is my code so far:

public class All_Challenges {

public static void main(String[] args) {
    System.out.println("Which class do you want to run?: ");
    System.out.println("1. The first class");

Class[] theFiles = new Class[31];
    theFiles[1] = Challenge_1_Whats_Your_Name.main(args);
    theFiles[1].main(args);
    }
}

The last two lines are giving me an error because they are making me change the class type from The void to type class and then making add a return statement. I have around 30 of these so I would prefer not to have to change my main method in all my other classes. What stuff should I write so that I don't have to do this. I think it's something to do with what "type" my array is. Or maybe it's to do with the line main.(args); Weird part is that it doesn't ask me to change the type when I don't call it from an array.


Solution

  • The problem is that you are trying to put a method to array of classes.

        Class[] theFiles = new Class[31];
        theFiles[1] = Challenge_1_Whats_Your_Name.class;
        try {
            theFiles[1].getMethod("main", String[].class).invoke(args);
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    

    That should work for you