Today I'll talk about a famous problem : restarting a Java application. It is especially useful when changing the language of a GUI application, so that we need to restart it to reload the internationalized messages in the new language. Some look and feel also require to relaunch the application to be properly applied.
A quick Google search give plenty answers using a simple :
This indeed basically works, but this answer that does not convince me for several reasons :
1) What about VM and program arguments ? (this one is secondary in fact, because can be solve it quite easily).
2) What if the main is not a jar (which is usually the case when launching from an IDE) ?
3) Most of all, what about the cleaning of the closing application ? For example if the application save some properties when closing, commit some stuffs etc.
4) We need to change the command line in the code source every time we change a parameter, the name of the jar, etc.
Overall, something that works fine for some test, sandbox use, but not a generic and elegant way in my humble opinion.
Ok, so my purpose here is to implement a method :
that could be wrapped in some jar library, and could be called, without any code modification, by any Java program, and by solving the 4 points raised previously.
Let's start by looking at each point and find a way to answer them in an elegant way (let's say the most elegant way that I found).
1) How to get the program and VM arguments ? Pretty simple, by calling a :
Concerning the program arguments, the Java property sun.java.command we'll give us both the main class (or jar) and the program arguments, and both will be useful.
2) First retrieve the java bin executable given by the java.home property :
The simple case is when the application is launched from a jar. The jar name is given by a mainCommand, and it is in the current path, so we just have to append the application parameters mainCommand[1..n] with a -jar to get the command to execute :
We'll suppose here that the Manifest of the jar is well done, and we don't need to specify either the main nor the classpath.
Second case : when the application is launched from a class. In this case, we'll specify the class path and the main class :
3) Third point, cleaning the old application before launching the new one.
To do such a trick, we'll just execute the Runtime.getRuntime().exec(cmd) in a shutdown hook.
This way, we'll be sure that everything will be properly clean up before creating the new application instance.
Run the runBeforeRestart that contains some custom code that we want to be executed before restarting the application :
And finally, call the
And we're done. Here is our generic method :