O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Clojure from Java

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.[304] 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:

  1. Load the Clojure code you want to use. This means reusing the standard require, use, or load functions provided in Clojure’s clojure.core namespace.

  2. Obtain references to the vars corresponding with each function or value defined in the namespaces you care about.

  3. Call the functions and use the values however your application requires.

All we need to demonstrate JavaClojure 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.[305]

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required