[ACCEPTED]-Is it possible to call the main method passing args[] from another method?-java
You can call the main
method as you would call 1 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 4 any other method, so if you have a class 3 Test with a main method, you can call it 2 from any other class like:
Test.main(new String[] { "a", "b" });
and this way you'll 1 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 6 this is not a good idea, the main() method 5 should only contain some very basic code 4 which calls the constructor. You shouldn't 3 call it directly, but rather create a new 2 instance of your other class which will 1 do all the initialization needed.
The answer is yes,
Since main
is a static
method and 2 is public method, you can do this (and it compiled 1 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 7 ordinary (static) method like this:
TheClass.main(new String[] { "lorem", "ipsum" });
As a 6 side note, you could declare the main method 5 like this:
public static void main(String... args) { ... }
and call it like
TheClass.main("lorem", "ipsum");
The bytecode produced 4 is the same (varargs are compiled to arrays), so 3 it is backward compatible in all ways (except 2 that it won't compile on non-vararg aware 1 java-compilers).
You could just rename your main and make 3 a new one, making it call the "new" main. At 2 least that's what I generally do when unit 1 testing
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.