gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:43:08 24 4
gpt4 key购买 nike

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

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

}
}

最佳答案

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

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

关于Java - 如何使用字符串调用类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787228/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com