Clojure Java Interop - a simple example


[Note: This post contains javascript which may not be rendered properly by feed readers]

Clojure lets you access Java classes directly. Here is a small demo.

Let's define a class:

Compile and save the resulting .class file in a directory "demo" under your current directory. Now, execute the command:

java -cp /home/pce/clojure-1.1.0/clojure.jar:. clojure.main

The "-cp" option sets the JAVA CLASSPATH to a list containing two names - one, the absolute name of the Clojure JAR file and the other, the current directory. Now, type the following in the Clojure REPL:

user=> (import '(demo counter))

The idea is to "import" the class `counter' from the package "demo". If Clojure does not print any error message, you can try:

user=> (counter/sqr 4)

You are calling the static function defined in class "counter" with parameter 4. It's as simple as that!

What if you wish to call the non-static member functions "increment" and "get"? You have to first create an object of type "counter":

user=> (def f (new counter))

That's it - `f' now refers to a counter object!

user=> (. f get)
user=> (. f increment)
user=> (. f get)

Yes - you can sort of read (. f get) as f.get() and (. f increment) as f.increment()!

There is another way to do the same thing:

user=> (.increment f)
user=> (.get f)

You can't get anything simpler than this, can you?

[Go to Code Clojure home] [Follow me on Twitter] [Go to home]