javaapplication-restart

How to make your java application restarts itself


I want to implement reset feature in my application which cleans up some directories, copies files etc. then in order to complete the process I need to restart it.

How to make application reruns itself? I think opening second instance and closing this one would be enough, altough it is not real restart.

My application's core is class extending JFrame but there is lot of static blocks which read class's extensions when the program is executed. I need to restart programatically my application so all of the static collection and blocks will be created/executed again.

It starts that way.

SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Window().createGUI();
        }
    });

This seems work fine:

public void restart() {
    /*  dispose();
    Window.main(null);*/
    StringBuilder cmd = new StringBuilder();
    cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
    for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        cmd.append(jvmArg + " ");
    }
    cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
    cmd.append(Window.class.getName()).append(" ");

    try {
        Runtime.getRuntime().exec(cmd.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.exit(0);
}

Solution

  • This is from the other topic but in the opposite to the accepted question in this other topic this one really works.

    public void restart() {
              StringBuilder cmd = new StringBuilder();
                cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java ");
                for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
                    cmd.append(jvmArg + " ");
                }
                cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" ");
                cmd.append(Window.class.getName()).append(" ");
    
                try {
                    Runtime.getRuntime().exec(cmd.toString());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.exit(0);
        }
    

    27/02/2018: I believe that Mark posted better solution: https://stackoverflow.com/a/48992863/1123020