开发者

Execute Java main method from within a Java desktop app in a different 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 c开发者_如何学运维lass 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.


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.


Very good question. Try to search into management API: http://cupi2.uniandes.edu.co/javadoc/j2se/1.5.0/docs/api/javax/management/package-frame.html

Good luck.

I am not sure that this API exists, but if it is it should be there. I'd personally used ProcessBuilder as you but specify explicit path to java by retrieving system properties of current process.


HSQLDB has a generic solution for invoking the main methods for multiple different processes. Use this class to invoke any process MainInvoker class source

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜