Showing posts with label Clojure from java. Show all posts
Showing posts with label Clojure from java. Show all posts

Sunday, March 7, 2010

Calling clojure script from java

Learned how to call clojure from java from Pablo's blog. Thank you, Pablo.

Add closure.jar to the java project( I have been using Eclipse). Use the following java code,


package pkg;

import clojure.lang.RT;
import clojure.lang.Var;

public class HelloWorld {
private static String resPath = "pkg/clap.clj";
public static void main(String[] args) {
System.out.println("Java hello world");
try {
RT.loadResourceScript(resPath);
Var mainVar = RT.var("pkg", "main");
mainVar.invoke(args);
} catch (Exception e) {
e.printStackTrace();
}
}
}


and the following clojure script in the same directory as the java source:

(ns pkg)

(defn main [args]
(println "Hello World!")
(println "Java main called clojure function with args: "
(apply str (interpose " " args))))


Notes:
1. The java package name matches the clojure namespace.
2. (apply str (interpose " " args))
- interpose is a function; arguments are " " and args. From the online documentation: Returns a lazy seq of the elements of coll separated by sep
- apply is a function; applies function str (the 1st argument) to the argument list, which is the sequence returned by interpose.
3. So many functions. Here is the Clojure API online documentation
4. Control-Space on import clojure. and I see some important packages:
- clojure.lang.*
- clojure.core.*
- clojure.test.*
- clojure.inspector.*
- clojure.xml.*
- clojure.asm.*
- clojure.asm.commons.*

Of course, the whole idea is to develop in clojure - not java - and deploy into a JVM. So we probably won't be using the above packages very much (if at all!)

I need to find some interesting work - not too hard, but potentially useful to somebody.