Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Java to Invoke another class' main method and return to the invoking code?

Tags:

java

public class A{     public static void main(String[] args)     {         //Main code     } }  public class B{     void someMethod()     {         String[] args={};         A.main();         System.out.println("Back to someMethod()");     } } 


Is there any way to do this? I found a method of doing the same using reflection but that doesn't return to the invoking code either. I tried using ProcessBuilder to execute it in a separate process but I guess I was missing out something.

like image 376
Aswin Parthasarathy Avatar asked Jun 13 '13 19:06

Aswin Parthasarathy


People also ask

Can we call a main method from another class in Java?

Solution: 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.

Can we return any value from main method?

As the main() method doesn't return anything, its return type is void. As soon as the main() method terminates, the java program terminates too. Hence, it doesn't make any sense to return from the main() method as JVM can't do anything with the return value of it.

Can Java run two main methods?

From the above program, we can say that Java can have multiple main methods but with the concept of overloading. There should be only one main method with parameter as string[ ] arg.

How do you call one method from another method in Java?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out.


1 Answers

Your code already nearly does it - it's just not passing in the arguments:

String[] args = {}; A.main(args); 

The main method is only "special" in terms of it being treated as an entry point. It's otherwise a perfectly normal method which can be called from other code with no problems. Of course you may run into problems if it's written in a way which expects it only to be called as an entry point (e.g. if it uses System.exit) but from a language perspective it's fine.

like image 65
Jon Skeet Avatar answered Oct 24 '22 10:10

Jon Skeet