14

Is there a way in java to get the command line arguments that were passed to a program outside of the main function?

I'm writing some code that's part of a larger application I don't control, and I'd like to know what the command line args were, without modifying the main function.

Note: I've seen how to get the JVM arguments, and how to get the arguments in main, but would like to get it in other parts of our app, without having them saved in the main function, which I don't control.

Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
  • Well, if you know the names of those arguments (and want to use names in the first place) you could pass them as system properties instead. Thus you'd be able to access them via `System.getProperty(name)`. – Thomas Jan 16 '17 at 14:39
  • 1
    Also check: http://stackoverflow.com/questions/2541627/how-do-i-get-the-commandline-that-started-the-process – JFPicard Jan 16 '17 at 14:40
  • 1
    You could try the property "sun.java.command". It gives you access to the full command that was used to execute the jar (I'll check the docs, wether this is portable between JVM-implementations). –  Jan 16 '17 at 14:48
  • @Paul - i just tried it, and for me on my mac at least, that totally worked... Thanks for suggesting it ! and the line to get it is pretty much `System.getProperty("sun.java.command");` – Brad Parks Jan 16 '17 at 14:54
  • 2
    @BradParks update: as the prefix "sun" suggests, this property is most likely a oracle-jre specific system property. I haven't found any resources to verify this, so please handle with care. –  Jan 16 '17 at 15:07
  • @Paul - not sure what you mean by "as the prefix" ? – Brad Parks Jan 16 '17 at 15:10
  • 2
    This also works on windows 7 with the oracle jre. – chris Jan 16 '17 at 15:15
  • @Paul - you should totally add this as an answer to the question this was a duplicate of, namely [this one](http://stackoverflow.com/q/5061367/26510). And good point about the "sun." prefix bit - i get ya now! – Brad Parks Jan 16 '17 at 15:24

1 Answers1

13

When starting the jvm this way: java -DmyArgument=myValue -jar your.jar you can get the value of myArgument everywhere in your java code with String myArg = System.getProperty("myArgument");

chris
  • 1,685
  • 3
  • 18
  • 28