Clojure:从Java调用Clojure

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

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

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

首先,我们通过Leinigen创建一个Clojure项目。

lein new hello_clojure

生成后目录结构如下:

修改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程序中。

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

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。

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

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

原文地址:https://www.cnblogs.com/ilovewindy/p/3818914.html