Clojure:从Java调用Clojure

咱们要在Java中调用Clojure有两种方法,一种是将Clojure代码生成class文件,另一种是经过Clojure RT方式直接在java程序中调用Clojure代码。两种方式各有优缺点,html

 

第一种方式的优势在于在Java调用class与日常的java代码没有任何区别,并且对IDE友好。而且因为是预编译了代码,在运行时会有一些速度优点。可是缺点是会损失一些Clojure动态语言的优点。第二种方式则和第一种正好相反。java

 

在这里,咱们只讲第一种方法。eclipse

 

首先,咱们经过Leinigen建立一个Clojure项目。函数

lein new hello_clojureurl

生成后目录结构以下:spa

 

修改project.clj文件以下:命令行

1 (defproject hello_clojure "0.1.0-SNAPSHOT"
2   :description "FIXME: write description"
3   :url "http://example.com/FIXME"
4   :license {:name "Eclipse Public License"
5             :url "http://www.eclipse.org/legal/epl-v10.html"}
6   :dependencies [[org.clojure/clojure "1.5.1"]]
7   :aot [hello-clojure.core]
8   :main hello-clojure.core)

注意其中:aot和:main的代码。:aot的意思是预编译hello-clojure.core程序。:main的意思是主函数入口位于hello-clojure.core程序中。code

 

修改hello_clojure目录下的core.clj程序以下:htm

1 (ns hello-clojure.core
2   (:gen-class
3     :methods [#^{:static true} [hello [String] String]]))
4 
5 (defn -hello
6   "Say Hello."
7   [x]
8   (str "Hello " x))
9 (defn -main [] (println "Hello from main"))

注意其中的关键代码:gen-class,经过它咱们就能够生成包含hello方法的class。blog

 

切换到命令行,运行以下命令:

lein compile

lein uberjar

这时会在target目录下生成hello_clojure-0.1.0-SNAPSHOT.jar和hello_clojure-0.1.0-SNAPSHOT-standalone.jar两个jar文件。若是目标项目没有Clojure类库的话,咱们能够使用standalone的jar包。

 

如今咱们能够在java程序中调用此jar包了。首先让咱们新建一个java项目,将刚刚生成的jar包引入到lib中。调用代码以下:

 1 package com.hello;
 2 
 3 import java.io.IOException;
 4 import hello_clojure.core;
 5 
 6 public class CallClojure {
 7     public static void main(String[] args) throws IOException {
 8         String callResult = core.hello("Neo");
 9         System.out.print(callResult);
10     }
11 }

能够看到这是很普通的java代码,没有任何特殊之处。这段代码输出的结果应为

Hello Neo

 

那么咱们再试试main方法,咱们直接在命令行中输入

java -jar target/hello_clojure-0.1.0-SNAPSHOT-standalone.jar

这时的输出结果应为

Hello from main

相关文章
相关标签/搜索