Programming

(Clojure) Invoking Clojure from Java

steloflute 2013. 3. 3. 22:25

http://en.wikibooks.org/wiki/Clojure_Programming/Tutorials_and_Tips#Invoking_Clojure_from_Java


Invoking Clojure from Java

The main site's Java Interop reference shows how you can call your Java code from Clojure. But because Clojure is implemented as a Java class library, you can also easily embed Clojure in your Java applications, load code, and call functions.

Repl.java and Script.java in the distribution are the canonical examples for loading code from a user or from a file. In this section we'll show how to use the same underlying machinery to load code and then manipulate it directly from Java.

Here's a script that defines a simple Clojure function.

; foo.clj
(ns user)
 
(defn foo [a b]
  (str a " " b))

And here's a Java class that loads the script, calls the foo function with some Java objects as arguments, and prints the returned object.

// Foo.java
 
import clojure.lang.RT;
import clojure.lang.Var;
 
public class Foo {
    public static void main(String[] args) throws Exception {
        // Load the Clojure script -- as a side effect this initializes the runtime.
        RT.loadResourceScript("foo.clj");
 
        // 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);
    }
}

Compile this and run it to see the printed result:

>javac -cp clojure.jar Foo.java

>java -cp clojure.jar Foo
Hi there

>

When Calling code from outside the classpath, the same effect can be achieved by running

clojure.lang.Compiler.loadFile("foo.clj");

From within the Java code instead of RT.loadResourceScript("foo.clj");