Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
Walle Avatar asked May 13 '11 08:05

Walle


People also ask

How do you start a new process in java?

There is only one way to create processes in Java, Runtime. exec() - basically it allows you to start a new JVM just as you would via the command line interface.

Can we execute main method 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.


1 Answers

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.

like image 55
Costi Ciudatu Avatar answered Oct 14 '22 17:10

Costi Ciudatu