Calling clojure from java

前端 未结 9 1503
梦毁少年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:43

    EDIT This answer was written in 2010, and worked at that time. See Alex Miller's answer for more modern solution.

    What kind of code are calling from Java? If you have class generated with gen-class, then simply call it. If you want to call function from script, then look to following example.

    If you want to evaluate code from string, inside Java, then you can use following code:

    import clojure.lang.RT;
    import clojure.lang.Var;
    import clojure.lang.Compiler;
    import java.io.StringReader;
    
    public class Foo {
      public static void main(String[] args) throws Exception {
        // Load the Clojure script -- as a side effect this initializes the runtime.
        String str = "(ns user) (defn foo [a b]   (str a \" \" b))";
    
        //RT.loadResourceScript("foo.clj");
        Compiler.load(new StringReader(str));
    
        // Get a reference to the foo function.
        Var foo = RT.var("user", "foo");
    
        // Call it!
        Object result = foo.invoke("Hi", "there");
        System.out.println(result);
      }
    }
    

提交回复
热议问题