Reputation: 2270
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?
Upvotes: 1
Views: 107
Reputation: 61031
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.
Upvotes: 2