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?
Though Java doesn't prefer main() method called from somewhere else in the program, it does not prohibit one from doing it as well. So, in fact, we can call the main() method whenever and wherever we need to.
When you run Java program, by right click on Java class with main method, it creates a Run Argument for that class. By the way, you can write your String args[] as String[] args as well, because both are valid way to declare String array in Java.
Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument.
We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With