Java-如何用字符串调用类的方法?

时间:2018-10-12 21:29:08

标签: java

我正在尝试使用来自控制台的输入来选择我要运行哪个类的主要方法。     打包运行;

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

    }
}

2 个答案:

答案 0 :(得分:1)

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

提供您的main方法为public static void main(String[] args)

答案 1 :(得分:0)

使用Reflection可以轻松解决此问题。看看下面的代码:

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));

    }
}