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? */
if(!currentJar.getName().endsWith(".jar"))
return;
/* Build command: java -jar application.jar */
final ArrayList<String> command = new ArrayList<String>();
command.add(javaBin);
command.add("-jar");
command.add(currentJar.getPath());
final ProcessBuilder builder = new ProcessBuilder(command);
builder.start();
System.exit(0);
}
Basically it does the following:
- Find the java executable (I used the java binary here, but that depends on your requirements)
- Find the application (a jar in my case, using the
MyClassInTheJar
class to find the jar location itself)
- Build a command to restart the jar (using the java binary in this case)
- Execute it! (and thus terminating the current application and starting it again)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…