Hanuman Chu
Hanuman Chu

Reputation: 65

Java - How do I call a class's method with a string?

I'm trying to use my input from the console to pick which class's main method I want to run. package run;

import java.lang.reflect.Method;
import java.util.Scanner;
import testing.*;

public class run {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException{
        Scanner input = new Scanner(System.in);
        String name = "testing."+input.nextLine();
        Class Program = Class.forName(name);
        //Try 1
        Program obj = new Program();
        //Got error "Program cannot be resolved to a type" on program and program
        //Try 2
        Program.main();
        //Got error "The method main() is undefined for the type Class" on main
        //Try 3
        Class.forName(name).main();
        //Got error "The method main() is undefined for the type Class<capture#2-of ?>" on main

    }
}

Upvotes: 0

Views: 82

Answers (2)

gherkin
gherkin

Reputation: 506

Class program = Class.forName(name);
program.getDeclaredMethod("main", String[].class).invoke(null, new Object[]{args});

provide your main method is public static void main(String[] args)

Upvotes: 1

Apoorv Agarwal
Apoorv Agarwal

Reputation: 336

This problem can be solved easily using Reflection. Check out the code below:

package run;

import java.lang.reflect.Method;
import java.util.Scanner;
import testing.*;

public class run {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, NegativeArraySizeException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Scanner input = new Scanner(System.in);
        String name = "testing."+input.nextLine();
        Class program = Class.forName(name);

        program.getMethod("main", String[].class).invoke(null, Array.newInstance(String.class, 0));

    }
}

Upvotes: 0

Related Questions