Calling Out to Java

Web Development with Clojure, Third Edition — by Dmitri Sotnikov, Scot Brown (82 / 107)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 The Re ad-Evaluate-Print Loop | TOC | Calling Methods 👉

One last thing that we’ll cover is how Clojure embraces its host platform to benefit from the rich ecosystem of existing Java libraries. In some cases, we may wish to call a Java library to accomplish a particular task that doesn’t have a native Clojure implementation. Calling Java classes is simple and follows the standard Clojure syntax fairly closely.

Importing Classes

When we wish to use a Clojure library, we employ :use and :require statements. However, when we wish to import a Java class, we have to use the :import statement.

​ (​ns​ myns
​ (:import java.io.File))

We can also group multiple classes from the same package in a single import, as follows:

​ (​ns​ myns
​ (:import [java.io File FileInputStream FileOutputStream]))

Instantiating Classes

To create an instance of a class, we can call new just as we would in Java.

​ (new File ​"."​)

We could also use a common shorthand for creating new objects:

​ (​File.​ ​"."​)

👈 The Re ad-Evaluate-Print Loop | TOC | Calling Methods 👉

Web Development with Clojure, Third Edition by Dmitri Sotnikov, Scot Brown can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.