Calling clojure from java

前端 未结 9 1507
梦毁少年i
梦毁少年i 2020-11-22 11:13

Most of the top google hits for \"calling clojure from java\" are outdated and recommend using clojure.lang.RT to compile the source code. Could you help with a

9条回答
  •  臣服心动
    2020-11-22 11:27

    EDIT: I wrote this answer almost three years ago. In Clojure 1.6 there is a proper API exactly for the purpose of calling Clojure from Java. Please Alex Miller's answer for up to date information.

    Original answer from 2011:

    As I see it, the simplest way (if you don't generate a class with AOT compilation) is to use clojure.lang.RT to access functions in clojure. With it you can mimic what you would have done in Clojure (no need to compile things in special ways):

    ;; Example usage of the "bar-fn" function from the "foo.ns" namespace from Clojure
    (require 'foo.ns)
    (foo.ns/bar-fn 1 2 3)
    

    And in Java:

    // Example usage of the "bar-fn" function from the "foo.ns" namespace from Java
    import clojure.lang.RT;
    import clojure.lang.Symbol;
    ...
    RT.var("clojure.core", "require").invoke(Symbol.intern("foo.ns"));
    RT.var("foo.ns", "bar-fn").invoke(1, 2, 3);
    

    It is a bit more verbose in Java, but I hope it's clear that the pieces of code are equivalent.

    This should work as long as Clojure and the source files (or compiled files) of your Clojure code is on the classpath.

提交回复
热议问题