虽然之前在线讨论中提供的一些信息可能已经过时,但从 Java 调用 Clojure 仍然相对简单。这是分步指南:
Clojure Jar 准备:
定义您的 Clojure 函数src/com/domain/tiny.clj:
(ns com.domain.tiny) (defn binomial "Calculate the binomial coefficient." [n k] (let [a (inc n)] (loop [b 1 c 1] (if (> b k) c (recur (inc b) (* (/ (- a b) b) c)))))) (defn -binomial "A Java-callable wrapper around the 'binomial' function." [n k] (binomial n k)) (defn -main [] (println (str "(binomial 5 3): " (binomial 5 3))) (println (str "(binomial 10042, 111): " (binomial 10042 111))))
Java代码:
创建一个调用 Clojure 函数的 Java 类:
import java.lang.reflect.Method; import com.domain.tiny; public class Main { public static void main(String[] args) { try { Method binomialMethod = Class.forName("com.domain.tiny").getMethod("binomial", int.class, int.class); Integer n = 5; Integer k = 3; Double result = (Double) binomialMethod.invoke(null, n, k); System.out.println("(binomial " + n + " " + k + "): " + result); n = 10042; k = 111; result = (Double) binomialMethod.invoke(null, n, k); System.out.println("(binomial " + n + ", " + k + "): " + result); } catch (Exception e) { System.err.println("Error calling Clojure function: " + e.getMessage()); e.printStackTrace(); } } }
使用适当的内容创建清单文件 (MANIFEST.MF) dependency:
Manifest-Version: 1.0 Class-Path: tiny.jar:clojure-x.y.z.jar Main-Class: Main
运行程序:
输出应类似于:
(binomial 5 3): 10.0 (binomial 10042, 111): 4.9068389575068143E263
以上是如何使用现代技术从 Java 高效调用 Clojure 函数?的详细内容。更多信息请关注PHP中文网其他相关文章!