1

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?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Queeg
  • 7,748
  • 1
  • 16
  • 42

2 Answers2

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

Queeg
  • 7,748
  • 1
  • 16
  • 42
  • Please be precise: does this print ALL elements of the command line, or is it just sufficient to acquire the exact path to the JVM/java that was used? – GhostCat May 11 '22 at 08:06
1

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.

user16320675
  • 135
  • 1
  • 3
  • 9
  • I tested that one and it does not give the full command line - not even all the VM arguments. – Queeg May 11 '22 at 07:44
  • 1
    very strange, works fine for me, see [screenshot](https://i.stack.imgur.com/TQq90.png) - but it sure does not return the full command line, as described in answer (and sorry that I do not provide full functional code to solve all your tasks) – user16320675 May 11 '22 at 07:50
  • Your screenshot does not show `java`, which could be different. And in my test also the classpath was missing. But the complete command line is what the question is targeting at. – Queeg May 11 '22 at 08:01