java 調用 clojure



這裏不介紹調用文本clojure然後jvm中執行的過程, 也不介紹手動aot 來編譯成class來給jvm調用。主要還是介紹下使用lein來打包成jar 然後java程序中調用,本人覺得這個是最舒服的做法。

具體可以參考http://walkwithoutrhythm.net/blog/2012/03/26/how-to-call-clojure-1-dot-3-functions-from-java/


lein  https://github.com/technomancy/leiningen


lein Tutorial https://github.com/technomancy/leiningen/blob/stable/doc/TUTORIAL.md



新建一個工程
$ lein new app hello

直接運行測試
$ lein run
Hello, World!



編輯文件 src/hello/core.clj
(ns hello.t
  (:gen-class
   :methods [#^{:static true} [jerry [String] String]]) 
    )

(defn -jerry [gophee] 
	(str "jerry like  tom !" gophee)
	)

注意這裏可能會遇到一個問題,默認的lein生成的project的project.clj是
(defproject my-stuff "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]]
  :main ^:skip-aot hello.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

打包後發現只有main的才生成name space的,可以修改成

(defproject hello "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.5.1"]]
  ;:main ^:skip-aot hello.core
  :main librarian-clojure.run
  :aot :all
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

當然也可以用正則表達式來定義name space
You can also specify regex as parameter for :compile option – it will compile only matched namespaces
可以參考
http://blog.japila.pl/2012/02/aot-compile-all-namespaces-in-a-clojure-project-aot-all-in-project-clj-leiningen/


打包到jar
$ lein uberjar



然後在eclipse 中添加hello-0.1.0-SNAPSHOT.jar

 寫個java類測試下

public class CallClass {

	
		public static void main(String[] args) {
		
			String  ss = hello.t.jerry(" test ");
                        System.out.println(ss);
		}
}	

輸出 jerry like  tom ! test


ok,完工





發佈了56 篇原創文章 · 獲贊 17 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章