In Java there's a simple way to get path of a running jar file:
MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()
But in Clojure we do not have class name, only namespace and functions. Same thing applies to the uncompiled scripts/REPL.
So my questions are:
By default the name of your class is the name of your AOT-compiled namespace (that's what gen-class is for), so you can simply use the namespace's class.
(ns foo.core
(:gen-class))
(defn this-jar
"utility function to get the name of jar in which this function is invoked"
[& [ns]]
;; The .toURI step is vital to avoid problems with special characters,
;; including spaces and pluses.
;; Source: https://stackoverflow.com/q/320542/7012#comment18478290_320595
(-> (or ns (class *ns*))
.getProtectionDomain .getCodeSource .getLocation .toURI .getPath))
(defn -main [& _]
(println (this-jar foo.core)))
Result of running:
$ java -cp foo-0.1.0-SNAPSHOT-standalone.jar foo.core
/home/rlevy/prj/foo/target/foo-0.1.0-SNAPSHOT-standalone.jar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With