For the moment, let’s assume that you would like to call into a Clojure library from Java, and that library does not define any types or classes. To use that codebase, you’ll need to tap into the Clojure “native” functions and constant values it defines in namespaces. Thankfully, doing so from Java is straightforward:
Load the Clojure code you want to use. This means reusing the
load functions provided in Clojure’s
Obtain references to the vars corresponding with each function or value defined in the namespaces you care about.
Call the functions and use the values however your application requires.
All we need to demonstrate Java→Clojure interop are two vars, one providing a function, the other some value. The value will come from a simple Clojure namespace:
Example 9-20. Simple Clojure namespace
(ns com.clojurebook.histogram) (def keywords (map keyword '(a c a d b c a d c d k d a b b b c d e e e f a a a a)))
The function we’ll use is
frequencies from the
clojure.core namespace; it accepts any seqable
value, and returns a map of the seq’s elements and counts of their
frequency of occurrence in the seq.
Here is a Java class that uses
frequencies with the
keywords value as well as many others.
Example 9-21. Using Clojure code in Example 9-20 from Java
package com.clojurebook; import java.util.ArrayList; import java.util.Map; import clojure.lang.IFn; import clojure.lang.Keyword; import clojure.lang.RT; import ...