1

UNIX shell programs have the convenient property that the first argument is the name of the invoked program. So I can write something like:

#!/bin/sh
echo "You ran $0."

And when I run it, I get:

$ sh foo.sh 
You ran foo.sh.

This is particularly useful when you want to catch a bad invocation and give a usage string, like:

Usage: foo.sh -a [AAAAA] -b [BBBBB] -c [CCCCC]

How can I do this for a JAR file invoked like java -jar MyJAR.jar? For Scala main, args(0) is just the first argument passed by the user, not the name of the invoked program. I want to be able to print out:

Usage: MyJAR.jar -a [AAAAA] -b [BBBBB] -c [CCCCC]

Any ideas?

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
Dan Barowy
  • 2,270
  • 24
  • 35

1 Answers1

2

You could try this:

val path = myClass.getClass.getProtectionDomain.getCodeSource.getLocation.getPath

This should work as long as myClass is an instance of a class defined in the jar file you are running.

dbyrne
  • 59,111
  • 13
  • 86
  • 103