2010-05-01 64 views
5

Clojure程序如何找到自己的MANIFEST.MF(假设它打包在JAR文件中)。Clojure程序读取自己的MANIFEST.MF

我想从我的“ - 主”的功能做到这一点,但我不能找到一个类下面的代码中使用:

(.getValue 
    (.. 
     (java.util.jar.Manifest. 
     (.openStream 
      (java.net.URL. 
      (str 
       "jar:" 
       (.. 
       (class **WHAT-GOES-HERE**) 
       getProtectionDomain 
       getCodeSource 
       getLocation) 
       "!/META-INF/MANIFEST.MF")))) 
     getMainAttributes) 
    "Build-number")) 

感谢。

+0

谢谢,这很有帮助。我做了一些重构,因为我对此很迷恋。这是我结束了: (DEFN得到功能定位 [符号] (..(类符号) getProtectionDomain getCodeSource 的getLocation)) (DEFN得到舱单的属性 [] (让[location(get-function-location get-manifest-attributes)] (when-not(nil?location) ( - >(str“jar:”location“!/META-INF/MANIFEST.MF)) (URL。) (.openStream) (Manifest。) (.getMainAttributes))))) – 2012-05-25 22:49:40

+0

更正:将符号传递给函数不是正常工作。我最终做了重命名get-function-location来获取位置并将get-location传递给类。 – 2012-05-25 23:45:12

回答

3

这似乎可靠地工作:

(defn set-version 
    "Set the version variable to the build number." 
    [] 
    (def version 
    (.getValue (.. (Manifest. 
     (.openStream 
     (URL. 
      (str "jar:" 
      (.getLocation 
       (.getCodeSource 
       (.getProtectionDomain org.example.myproject.thisfile))) 
      "!/META-INF/MANIFEST.MF")))) 
     getMainAttributes) 
     "Build-number"))) 
0

我发现了一个可行的答案,但我愿意提出改进建议,特别是将号召更换为Class/forName

(defn -main [& args] 
    (println "Version " 
    (.getValue 
     (.. 
     (Manifest. 
      (.openStream 
      (URL. 
       (str 
       "jar:" 
       (.. 
        (Class/forName "org.example.myproject.thisfile") 
        getProtectionDomain 
        getCodeSource 
        getLocation) 
       "!/META-INF/MANIFEST.MF")))) 
     getMainAttributes) 
     "Build-number"))) 
1

我发现我的版本的眼睛变得更轻松:

(defn manifest-map 
    "Returns the mainAttributes of the manifest of the passed in class as a map." 
    [clazz] 
    (->> (str "jar:" 
      (-> clazz 
       .getProtectionDomain 
       .getCodeSource 
       .getLocation) 
      "!/META-INF/MANIFEST.MF") 
     clojure.java.io/input-stream 
     java.util.jar.Manifest. 
     .getMainAttributes 
     (map (fn [[k v]] [(str k) v])) 
     (into {}))) 

(get (manifest-map MyClass) "Build-Number") 
1

这里有一个阅读的版本,大概就这么简单,我能得到它!

(when-let [loc (-> (.getProtectionDomain clazz) .getCodeSource .getLocation)] 
    (-> (str "jar:" loc "!/META-INF/MANIFEST.MF") 
     URL. .openStream Manifest. .getMainAttributes 
     (.getValue "Build-Number"))) 
0

还有clj-manifest,基本上提供了这个功能,使用类似于这里找到其他的答案的电话。