java 调用 clojure

来源:互联网 发布:长相土气的女明星知乎 编辑:程序博客网 时间:2024/05/16 00:26



这里不介绍调用文本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 runHello, 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,完工





0 0