Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Java main method from within a Java desktop app in a different JVM

Tags:

java

jvm

I have a desktop app and when someone presses a button I want it to kick off another JVM that executes a class' main method. My desktop app already depends on the jar that contains the class with the main method that I want to execute.

Currently I've got the following code, however, I was hoping their was a more elegant way of doing this:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("java -jar another.jar");

I know I can use ProcessBuilder too.

Is there no way such as (excuse the pseudo code):

Jvm.execute(Main.class);

Since the Main class that I want to call already exists in my classpath, it just feels weird to have to run the java command via Runtime.

like image 717
digiarnie Avatar asked Oct 26 '22 01:10

digiarnie


1 Answers

Why do you need to execute this Main class in another JVM? It only complicates things.

Usually just Main.main(args) will be OK, however:

If you want to isolate that program from your program, just run it under another classloader - see URLClassLoader documentation. Notice that even complex Java application servers don't create many processes (usually it's just one JVM process), and isolate deployed WARs and EARs with just classloaders. You may think of classloader as a JVM's equivalent of process.

If that another program does some 'insecure' operations, use Java's security mechanism from java.security and prevent that program from doing those operations.

If that another program calls System.exit() and this stops your program, it's enough to use the security mechanism, and forbid that program to call System.exit() - see System.exit() Javadoc. Then you can just catch SecurityException and ignore it.

like image 161
iirekm Avatar answered Nov 02 '22 21:11

iirekm