How to restart a Java application, remembering its command line arguments

I have a Java application. It can be launched using a pair of command line flags. I want to provide the ability to "restart" the application by the user.

Currently, we save the arguments in the control file, read it when the application restarts. What is the best way to restart the application - how to save command line arguments?

+4
source share
5 answers

Using RuntimeMXBean, you can get, Classpath, Bootclasspath, etc.

package com; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; class JMXTest { public static void main(String args[]) { try { for ( int i = 0 ; i < args.length ; i++ ) System.out.println( "args :" + args[i] ); RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean(); System.out.println( "boot CP:" + mx.getBootClassPath() ); System.out.println( " CP:" + mx.getClassPath() ); System.out.println( "cmd args:" + mx.getInputArguments() ); } catch( Exception e ) { e.printStackTrace(); } } } 
+2
source

cause new use

 java -jar appname.jar arg1 arg2 

close current using

 System.exit(0); 

Here you will not encounter the problem of saving arg

Here is an example for calling commands from a java application

+1
source

In any case, you have to persist in the command line arguments. If the set of arguments is fairly fixed, consider writing a small package or shell script file that does nothing but call java with this set of arguments.

If you just want to run it once with arguments, and then if you restart the application without arguments, you want it to use the arguments of the previous call, do something like this:

 pubic static void main(String[] args) { if (args.length == 0) args = readArgsFromFile(); else writeArgsToFile(); // .. } 

Sidenote: For simplicity, I reused args . For better code, if necessary, copy the received or saved parameters to another data structure, another array, property instance, ...

+1
source

It varies depending on the user's OS if you really want to make it cross-platform compatible. Then you must provide the initial scripts: shell for Linux, such as OS / bat for Windows, these scripts configure the class path and arguments.

I don't think creating a restart button in an application is a wise decision, but if you need something like a โ€œrestart eclipseโ€, you should take a look at RuntimeMXBean, which can get the path to the load class for you.

0
source

Why not serialize and create the object again from disk on restart?

To do this, you need to implement the Serializable interface in the "CommandLineParams" class.

I think this is the most structured way to accomplish what you are trying to do.

0
source

All Articles