'Get full command line from Java [duplicate]

How can I from within Java code find out which and how the running JVM was launched? My code shall spawn another Java process hence I'd be especially interested in the first parameter - which usually (in C, Pascal, Bash, Python, ...) points to the currently running executable.

So when a Java application is run like

d:\openjdk\bin\java -Xmx500g -Dprop=name -jar my.jar param1 param2

I can access command line parameters in my main method like

public class Main {
    public static void main(String[] args) {
        System.out.println("main called with " + args);
    }
}

but that will deliver access to param1 and param2 only. How would I get the full command line?



Solution 1:[1]

Following Determining location of JVM executable during runtime I found the real answer to be:

ProcessHandle.current().info().commandLine().orElseThrow();

It returns the full command line as perceived by the operating system and thus contains all information: executable, options, main class, arguments, ...

Thank you, @XtremeBaumer

Solution 2:[2]

To get the command, use ProcessHandle adapted from your answer:

String command = ProcessHandle
                 .current()
                 .info()
                 .command()
                 .orElse("<unable to determine command>"); // .orElseThrow()  to get Exception

Use the Runtime Management Bean RuntimeMXBean to obtain the VM arguments and the class path, like in:

RuntimeMXBean mxBean = ManagementFactory.getRuntimeMXBean();
String classPath = mxBean.getClassPath();
List<String> inputArgs = mxBean.getInputArguments();

This will return all arguments passed to the virtual machine, not the parameters passed to the main method.


The code source can be get from the ProtectionDomain of the class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2