简体   繁体   中英

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={};
        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.

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 (eg if it uses System.exit ) but from a language perspective it's fine.

Yes you can do call A.main() .

You can do this:

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

If you don't care about the arguments, then you can do something like:

public static void main(String ... args)

and call it with:

A.main(); //no args here

There's nothing magic about the name "main". What you've sketched ought to work, so your problem must be something else. Test my claim by changing the name of "main" to something else, I bet it still doesn't work.

Actually, you can call main method like the way you have just asked but not the way you have done it. First, every execution process starts from the main method. So, if you want to do it the way you want you can do right this way. This code will execute Hello! World Hello! World eight times:

class B
{
  B()
  {
    while(A.i<8)
    {
      String a[]={"Main","Checking"};
      A.main(a);
    }
    System.exit(0);
  }

}

class A
{
  public static int i=0;
  public static void main(String args[])
  {
    System.out.println("Hello! World");
    i++;
    B ob=new B();
  }
}

` The iteration part, you can leave it if you want. I Hope I gave you the solution just the way you wanted. :)

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

Just be aware: from purely what you have up there, the main method is still the entry point to the program. Now, if you are trying to run the main method in a new PROCESS, this is a different story.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM