Azfar Niaz Azfar Niaz - 1 year ago 127
Java Question

How can I restart a Java application?

How can I restart a Java AWT application? I have a button to which I have attached an event handler. What code should I use to restart the application?

I want to do the same thing that

do in a C# application.

Answer Source

Of course it is possible to restart a Java application.

The following method shows a way to restart a Java application:

public void restartApplication()
  final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
  final File currentJar = new File(MyClassInTheJar.class.getProtectionDomain().getCodeSource().getLocation().toURI());

  /* is it a jar file? */

  /* Build command: java -jar application.jar */
  final ArrayList<String> command = new ArrayList<String>();

  final ProcessBuilder builder = new ProcessBuilder(command);

Basically it does the following:

  1. Find the java executable (I used the java binary here, but that depends on your requirements)
  2. Find the application (a jar in my case, using the MyClassInTheJar class to find the jar location itself)
  3. Build a command to restart the jar (using the java binary in this case)
  4. Execute it! (and thus terminating the current application and starting it again)