在Java里面调用 Clojure
提前编译的Clojure函数如果是静态的函数的话,那么它们可以被java程序调用。可以通过把函数的元数据项: :static 设置为 true 来达到这个目的。语法是这样的:
(ns namespace
(:gen-class
:methods [#^{:static true} [function-name [param-types] return-type]]))
让我们看一个例子:下面是一个名字叫做Demo.clj的文件,它的路径是 src/com/ociweb/clj。
(ns com.ociweb.clj.Demo
(:gen-class
:methods [#^{:static true} [getMessage [String] String]]))
# Note the hyphen at the beginning of the function name!
(defn -getMessage [name]
(str "Hello, " name "!"))
下面是一个叫做 Main.java 的java文件,它和 src 以及 classes 在同一个目录。
import com.ociweb.clj.Demo; // class created by compiling Clojure source file
public class Main {
public static void main(String[] args) {
String message = Demo.getMessage("Mark");