Calling Java methods and accessing Java objects from Clojure
Though the Clojure language looks quite different from Java, Clojure provides full access to Java. This enables Clojure to make use of huge Java assets very efficiently. In general, calling Java assets from Clojure is much simpler and results in less code than calling them from Java. Another big advantage is REPL, which makes programming fun and faster.
Getting ready
In this recipe, we don't use an external library, so the only necessary thing is to start REPL to run code.
How to do it...
We will learn how to instantiate objects, call instance and class methods, access fields and inner classes, and reference classes. Then, we will learn how to manipulate Java arrays.
Instantiating objects
To instantiate an object from a class, use the following syntax:
(ClassName. arg1 arg2 ...)
For instance, to instantiate a new String
object the syntax is as follows:
(String. "abc") ;;=> "abc" (Integer. 1) ;;=> 1 ...