开发者

Is it possible to call the main method passing args[] from another method?

开发者 https://www.devze.com 2023-01-24 03:46 出处:网络
I\'m trying to call the main method of a class from another method passing arguments like when running the class from the command line. Is there a way开发者_开发问答 to do this?You can call the main m

I'm trying to call the main method of a class from another method passing arguments like when running the class from the command line. Is there a way开发者_开发问答 to do this?


You can call the main method as you would call any other (static) method:

MyClass.main(new String[] {"arg1", "arg2", "arg3"});

Example:

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


Yes, the main method can be called like any other method, so if you have a class Test with a main method, you can call it from any other class like:

Test.main(new String[] { "a", "b" });

and this way you'll pass "a" and "b" as the parameters.


Have you tried something like :

// In your method
String[] yourArgs = new String[] {"foo", "baz", "bar"};
YourClassWithMain.main(yourArgs);

But I think this is not a good idea, the main() method should only contain some very basic code which calls the constructor. You shouldn't call it directly, but rather create a new instance of your other class which will do all the initialization needed.


The answer is yes,

Since main is a static method and is public method, you can do this (and it compiled on my case):

/**
 * @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");

    }
}


Sure, you can call the main-method just as an ordinary (static) method like this:

TheClass.main(new String[] { "lorem", "ipsum" });

As a side note, you could declare the main method like this:

public static void main(String... args) { ... }

and call it like

TheClass.main("lorem", "ipsum");

The bytecode produced is the same (varargs are compiled to arrays), so it is backward compatible in all ways (except that it won't compile on non-vararg aware java-compilers).


You could just rename your main and make a new one, making it call the "new" main. At least that's what I generally do when unit testing

0

精彩评论

暂无评论...
验证码 换一张
取 消