Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Tooling and Interop

Java Interop

Use any Java library from Clojure: import, constructors, instance and static methods, fields, doto, type hints, arrays, exceptions, proxy, reify and calling Clojure from Java.

Clojure is hosted on the JVM, and that is one of its best features: every Java class, from java.util.UUID to a database driver, is available with almost no ceremony. There is no wrapper layer to write. Calling Java from Clojure is direct and fast, and Clojure's data structures are themselves Java objects (java.util.List, Map and friends).

Importing and creating objects

CLOJURE
(import '(java.util Date UUID Random)
        '(java.time LocalDate))

(def d (Date.))              ; constructor: ClassName. args
(def r (Random. 42))         ; (Random. 42) = new Random(42)
(def id (UUID/randomUUID))   ; static method

A trailing dot on a class name calls the constructor (a shorthand for (new Date)). Inside an ns form, use (:import (java.util Date UUID)). A fully qualified class name works without import: (java.util.Date.).

Methods and fields

Instance methods are called with the method name first, then the object:

CLOJURE
(.toUpperCase "hello")        ;=> "HELLO"      ; "hello".toUpperCase()
(.substring "clojure" 0 3)    ;=> "clo"
(.nextInt r 100)              ;=> a number below 100
(.length "abc")               ;=> 3

Static methods and static fields use a slash:

CLOJURE
(Math/sqrt 16.0)         ;=> 4.0
(Integer/parseInt "42")  ;=> 42
Math/PI                  ;=> 3.141592653589793
(System/getProperty "user.dir")

Instance fields use (.-field obj); public fields are rare in Java, but it appears in code like (.-x point).

Chaining with .. and doto

.. chains a series of calls, each applied to the previous result: (.. System (getProperties) (get "os.name")) means System.getProperties().get("os.name"). In most code, the thread-first macro -> reads better:

CLOJURE
(-> "  hello "
    .trim
    .toUpperCase
    (.replace "L" "_"))
;=> "HE__O"

doto calls several methods on one object and returns the object, perfect for builders and mutable setup code:

CLOJURE
(doto (java.util.ArrayList.)
  (.add "a")
  (.add "b"))
;=> ["a" "b"]

Collections and conversion

Java collections can be used with Clojure's sequence functions, because they are seqable:

CLOJURE
(def jl (java.util.ArrayList. [3 1 2]))
(sort jl)                 ;=> (1 2 3)
(map inc jl)              ;=> (4 2 3)
(into [] jl)              ;=> [3 1 2]

And the reverse is also true: Clojure vectors implement java.util.List, maps implement java.util.Map, and functions implement Runnable and Callable, so you can pass them to Java APIs:

CLOJURE
(.start (Thread. (fn [] (println "on another thread"))))
(.get (.submit executor #(+ 1 2)))

Use (into-array String ["a" "b"]) for Java arrays, aget/aset to access them, and (vec array) to convert back. to-array makes an Object[].

Type hints and reflection

Java method calls need to know the object's class. When Clojure cannot tell at compile time, it falls back to reflection, which works but is slow. A type hint (^ClassName) tells the compiler the type:

CLOJURE
(set! *warn-on-reflection* true)

(defn shout [s] (.toUpperCase s))         ; Reflection warning printed
(defn shout [^String s] (.toUpperCase s)) ; no warning, direct call

Turn on *warn-on-reflection* during development and fix warnings in hot code. Primitive hints (^long, ^double) help numeric loops: (defn add [^long a ^long b] (+ a b)).

Exceptions

Java exceptions use try, catch and finally, and throw:

CLOJURE
(try
  (Integer/parseInt "abc")
  (catch NumberFormatException e
    (println "bad number:" (.getMessage e))
    -1)
  (finally (println "done")))

Clojure also offers ex-info for data-carrying exceptions: (throw (ex-info "bad input" {:field :age})), read back with ex-data. Prefer it for your own errors.

Implementing interfaces

reify creates an anonymous implementation, and proxy extends a class (with possible overrides):

CLOJURE
(def counter
  (reify java.util.function.Supplier
    (get [_] 42)))
(.get counter)   ;=> 42

(def t (proxy [Thread] []
         (run [] (println "proxy thread"))))

For named, reusable types, deftype/defrecord can implement Java interfaces directly, and gen-class with AOT compilation produces a real class for Java code to extend.

Calling Clojure from Java

From Java, use the clojure.java.api.Clojure class:

Java
IFn plus = Clojure.var("clojure.core", "+");
Object result = plus.invoke(1, 2);   // 3

IFn require = Clojure.var("clojure.core", "require");
require.invoke(Clojure.read("my-app.core"));
IFn greet = Clojure.var("my-app.core", "greet");
greet.invoke("Ana");

Or compile with (:gen-class) to produce a class with a static main method, which is how java -jar app.jar runs your program.

Common mistakes

  • Mixing up .method and Class/static. A dot-first symbol is an instance method call; a slash is static.
  • Passing a Clojure vector where an array is needed. Use into-array.
  • Reflection in hot paths. Hint your types.
  • Overloaded method confusion. When Clojure cannot select the right overload, hint the argument: (.println ^PrintStream out ^String s).
  • Java nulls. A method that returns null returns nil; check with nil?, or wrap with some->.

Try it: interop-style calls in JavaScript

JavaScript is also a hosted language, so a Clojure-flavored doto, .. and -> over JavaScript objects shows the same idea: threading and building without temporary variables.

JS doto and threading

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: try, catch, finally with ex-info

JS Exceptions carrying data

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you create a java.util.Date object?

    A trailing dot calls the constructor: (Date.) is the same as (new Date).
  2. 2. What is the Clojure form of Math.sqrt(16.0)?

    Static methods use Class/method; instance methods use .method with the object first.
  3. 3. Why add type hints like ^String?

    Hints let the compiler resolve the method at compile time. Enable warn-on-reflection to find the places that need them.
  4. 4. What does doto return?

    doto runs the calls for effect and returns the object it was given.

Summary

  • import, (Class. args), (.method obj), (Class/static) and (.-field obj) cover most interop.
  • doto, .. and -> keep Java calls tidy; Java collections work with Clojure's sequence functions.
  • Clojure functions implement Runnable/Callable; reify and proxy implement interfaces and classes.
  • Hint types and watch for reflection warnings; use try/catch for Java exceptions and ex-info for your own.
  • Java can call Clojure with clojure.java.api.Clojure.

Next: Testing, spec and the REPL