Search code examples
javamultithreadingprocessprogram-entry-point

How can I start a 'main' in a new process in Java?


The question is rather simple. How can I start a main method in another java process? Now I do it like this:

startOptions = new String[] {"java", "-jar", "serverstart.jar"};
new ProcessBuilder(startOptions).start();

But they asked me to do it not with an external .jar file. The serverstart.jar obviously has a main method, but it it possible to call that main method in another process, without calling the .jar file?

I'm thinking of something like this:

new ProcessBuilder(ServerStart.main(startOptions)).start();

But I don't know if anything like that exists.


Solution

  • Assuming a new thread with a new classloader is not enough (I would vote for this solution though), I understand you need to create a distinct process that invokes a main method in a class without having that declared as "jar main method" in the manifest file -- since you don't have a distinct serverstart.jar anymore.

    In this case, you can simply call java -cp $yourClassPath your.package.ServerStart, as you would do for running any java application when you don't have (or don't want to use) the manifest Main-Class.