Clojure Java Interop - a simple example
2010-5-1
[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) 16 user=>
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) 0 user=> (. f increment) nil user=> (. f get) 1 user=>
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) nil user=> (.get f) 2 user=>
You can't get anything simpler than this, can you?
[Go to Code Clojure home] [Follow me on Twitter] [Go to pramode.net home]