I am quite a newbie to Clojure. I am trying to build my computational units (pure functions) in Clojure and bind all these functions into a program using Java.
For accessing Clojure in Java, I have done one thing i.e. Ahead-of-time compilation and class generation. But it looks cumbersome and weakens the idea of using Clojure into my application. So my question is have anyone tried to access Clojure functions in Java (excluding class generation and AOT compilation)? If not, then how to interlink these computational units (or Clojure functions) into a program (where there are several methods interlinked with each other) using purely Clojure?
2 Answers 2
Just as an overview the general process is:
- include the clojure runtime:
import clojure.lang.RT; - use the runtime to load your namespace (which will compile it):
RT.loadResourceScript("path/core.clj"); - get the iFn Object for the function you would like to call:
RT.var("mynamespace.core", "main") - and call the
invokemethod on that object
3 Comments
Have a look at my clojure-utils library. There are a lot of handy tools here for calling Clojure code from Java.
Here's a trivial demonstration:
import mikera.cljutils.Clojure;
public class DemoApp {
public static void main(String [] args) {
String s = "(+ 1 2)";
System.out.println("Evaluating Clojure code: "+s);
Object result=Clojure.eval(s);
System.out.println("=> "+ result);
}
}
I prefer to avoid AOT compilation: instead use the utilities in mikera.cljutils.Clojure to load, compile and execute Clojure code dynamically at runtime.