Aswin Parthasarathy Aswin Parthasarathy - 1 month ago 4x
Java Question

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

public class A{
public static void main(String[] args)
//Main code

public class B{
void someMethod()
String[] args={};
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
to execute it in a separate process but I guess I was missing out something.


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

String[] 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.