Calling Clojure From Java

While using Java APIs from Clojure is common due to Clojure’s embrace of the host platform, there are times when you’ll need to invoke Clojure directly from Java. For these cases, Clojure provides a Java API that can be used to directly access Clojure namespaces, vars, and functions.

The main entry point for the Clojure Java API is the clojure.java.api.Clojure class, which provides a few static methods for reading data, finding vars, and invoking unctions. With this handful of tools, you can invoke almost any aspect of Clojure.

For example, in a Java program, you can find the + function by using the var method of the Clojure class, which takes the namespace and name of a var and returns its value (in this case a function). All Clojure function instances implement the clojure.lang.IFn interface, which can be invoked with arguments:

 IFn plus = Clojure.var(​"clojure.core"​, ​"+"​)​;
 System.out.println(plus.invoke(1, 2, 3))​;

Note that the Java interfaces for Clojure functions generally take Object and return Object.

The Clojure class also provides a read method that can be used to read literal data into Clojure data structures:

 Object vector = Clojure.read(​"[1 2 3]"​)​;

By default, the Clojure Java API requires clojure.core, and thus all core functions are available without needing to load them. When you need to load another namespace, you can do so using require through the var interface to load namespaces just like you would at the REPL:

 IFn require = Clojure.var(​"clojure.core"​, ​"require"​)​;
 require.invoke(Clojure.read(​"clojure.set"​))​;

That covers the basics of using the Clojure Java API. As you can see, the tools provided cover just the basics of reading, function lookup, and invocation, but that’s enough to handle the majority of Clojure usage. Next we’ll look at how to handle catching and throwing exceptions in our Clojure code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.5.201