How to get VM arguments from inside of Java application?
At startup pass this -Dname=value
and then in your code you should use
value=System.getProperty("name");
to get that value
I found that HotSpot lists all the VM arguments in the management bean except for -client and -server. Thus, if you infer the -client/-server argument from the VM name and add this to the runtime management bean's list, you get the full list of arguments.
Here's the SSCCE:
import java.util.*;
import java.lang.management.ManagementFactory;
class main {
public static void main(final String[] args) {
System.out.println(fullVMArguments());
}
static String fullVMArguments() {
String name = javaVmName();
return (contains(name, "Server") ? "-server "
: contains(name, "Client") ? "-client " : "")
+ joinWithSpace(vmArguments());
}
static List<String> vmArguments() {
return ManagementFactory.getRuntimeMXBean().getInputArguments();
}
static boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static String javaVmName() {
return System.getProperty("java.vm.name");
}
static String joinWithSpace(Collection<String> c) {
return join(" ", c);
}
public static String join(String glue, Iterable<String> strings) {
if (strings == null) return "";
StringBuilder buf = new StringBuilder();
Iterator<String> i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext())
buf.append(glue).append(i.next());
}
return buf.toString();
}
}
Could be made shorter if you want the arguments in a List<String>
.
Final note: We might also want to extend this to handle the rare case of having spaces within command line arguments.
With this code you can get the JVM arguments:
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();