Clojure:如何获取正在运行的JAR /根源目录的路径?

ffr*_*end 8 jar path clojure

在Java中,有一种简单的方法来获取正在运行的jar文件的路径:

MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()
Run Code Online (Sandbox Code Playgroud)

但是在Clojure中我们没有类名,只有名称空间和函数.同样的事情适用于未编译的脚本/ REPL.

所以我的问题是:

  1. 我们如何找到运行jar文件路径
  2. 我们如何找到未编译源文件路径

rpl*_*evy 8

默认情况下,类的名称是AOT编译的命名空间的名称(这是gen-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)))
Run Code Online (Sandbox Code Playgroud)

运行结果:

$ java -cp foo-0.1.0-SNAPSHOT-standalone.jar foo.core
/home/rlevy/prj/foo/target/foo-0.1.0-SNAPSHOT-standalone.jar
Run Code Online (Sandbox Code Playgroud)


Kev*_*vin 1

我还没有尝试过这个,但似乎你所需要的只是一个类实例。例如,您可以不这样做吗:

(-> (new Object) (.getClass) (.getProtectionDomain) (.getCodeSource) (.getLocation) (.getPath))
Run Code Online (Sandbox Code Playgroud)