开发者

Call new JVM from existing JVM

开发者 https://www.devze.com 2023-04-01 22:07 出处:网络
I am writing GUI application, and I want to perform a restart of the application in case the user did some changes.

I am writing GUI application, and I want to perform a restart of the application in case the user did some changes.

Currenty I have once main call with the method startGui which initialises the gui. I want to know ho开发者_如何转开发w I can call this method again but with a new JVM from the existing JVM.


I don't think you can do that from within the VM. Instead, you probably need a dispatcher process (It could be a shell script, but it could be any other process as well, including a Java Process).

Anyway, you need to end the current process (using System.exit(someCode)), let your dispatcher analyze the return code and let it restart this application for a given return code.


Here is how I do this in my current project. It preserves the process arguments, the JVM arguments, and the classpath.

private static void restart(String[] args) throws IOException {
    RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
    List<String> jvmArgs = mx.getInputArguments();
    String cp = mx.getClassPath();

    List<String> listArgs = new ArrayList<String>();
    listArgs.add("java");
    listArgs.addAll(jvmArgs);
    listArgs.add("-cp");
    listArgs.add(cp);
    listArgs.add(Main.class.getName());
    listArgs.addAll(Arrays.asList(args));

    String[] res = new String[listArgs.size()];
    Runtime.getRuntime().exec(listArgs.toArray(res));

    System.exit(0);
}

Note that args is the argument received by the main method. It has to be memorized somewhere.

0

精彩评论

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