开发者

Java respawn process

开发者 https://www.devze.com 2023-01-03 08:06 出处:网络
I\'m making an editor-like program. If the user chooses File->Open in the main window I want to start a new copy of the editor process with the chosen filename as an argument. How开发者_如何学Goever,

I'm making an editor-like program. If the user chooses File->Open in the main window I want to start a new copy of the editor process with the chosen filename as an argument. How开发者_如何学Goever, for that I need to know what command was used to start the first process:

java -jar myapp.jar blabalsomearguments // --- need this information
> Open File (fileUrl)
> exec("java -jar myapp.jar blabalsomearguments fileUrl");

I'm not looking for an in-process solution, I've already implemented that. I'd like to have the benefits that seperate processes bring.


Since you are launching Java -> Java, you can use the existing classpath to set the classpath on the command line. This type of thing works really nice in the dev environment too.

ProcessBuilder selfLauncher = new ProcessBuilder(
 "java", "-cp", System.getProperty("java.class.path"),
 "com.my.mainClass" );
selfLauncher.start();

Update: For executable jar files, you will have a classpath which is simply the relative path to the jar file itself. If you want the command line arguments, you will have to save them from main, and re-apply them when launching.

You can see this by packing the following program into a jar. I'm not actually sure what happens if you have jars inside the executable jar file. They probably show up in the classpath.

public class TestJarPath {
    public static void main(String args[]) throws Exception {
        for (String s : args)
         System.out.print("[" + s + "] ");
        System.out.println();

        String cp = System.getProperty("java.class.path");
        for (String s : cp.split(";"))
          System.out.println(s);
    } 
}

For java -jar ..\tst.jar X, you get output like:

[X]
..\tst.jar


If all else fails, try writing a batch/shell script to launch your app. In windows you can pass %CmdCmdLine% to Java to get the entire command line.

See http://www.robvanderwoude.com/parameters.php


As far as I know is there no portable way to get this info. I found a property in the gcj runtime but I doubt this will cover a large percentage of the users.

I think the accepted practice is "Try and Pray" :

Hope it is on the path, (the path IS available, so that can be checked)

if not, check if JAVA_HOME is defined, and use that to find java.

if not check in the most likely places on all OS's you have received bug reports for.

Well, it is messy... porbably best to check for JAVA_HOME and the path and ask the user to configure a JVL explicitely if that fails.

0

精彩评论

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