我想从另一个方法调用一个类的主方法,并像在命令行中运行该类时传递参数一样传递参数。是否有一种方法可以做到这一点?
我想从另一个方法调用一个类的主方法,并像在命令行中运行该类时传递参数一样传递参数。是否有一种方法可以做到这一点?
您可以像调用任何其他(静态)方法一样调用main
方法:
MyClass.main(new String[] {"arg1", "arg2", "arg3"});
例子:
class MyClass {
public static void test() {
MyClass.main(new String[] {"arg1", "arg2", "arg3"});
}
public static void main(String args[]) {
for (String s : args)
System.out.println(s);
}
}
是的,main方法可以像其他方法一样被调用,因此如果你有一个名为Test的类,它有一个main方法,你可以从任何其他类中调用它,例如:
Test.main(new String[] { "a", "b" });
这样,你就可以将 "a" 和 "b" 作为参数传递。
你尝试过类似以下的方法吗:
// In your method
String[] yourArgs = new String[] {"foo", "baz", "bar"};
YourClassWithMain.main(yourArgs);
但我认为这不是一个好主意,main()方法应该只包含一些非常基本的代码来调用构造函数。你不应该直接调用它,而是创建另一个类的新实例,该实例将执行所有所需的初始化。
main
是一个static
方法并且是一个public方法,所以你可以这样做(在我的情况下编译通过):/**
* @author The Elite Gentleman
*
*/
public class Test {
/**
*
*/
public Test() {
super();
// TODO Auto-generated constructor stub
Test.main(new String[] {"main"}); //Yes, it works and compiles....
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello");
}
}
main
方法,如下所示:TheClass.main(new String[] { "lorem", "ipsum" });
public static void main(String... args) { ... }
然后像这样调用它
TheClass.main("lorem", "ipsum");
生成的字节码是相同的(varargs被编译为数组),因此在所有方面都具有向后兼容性(除了它无法在不支持vararg的java编译器上编译)。
你可以重命名你的主函数并创建一个新的,让它调用“新”的主函数。至少这是我在单元测试时通常做的。