1

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?

Burhan Ali
  • 2,258
  • 1
  • 28
  • 38

2 Answers2

3

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 invoke method on that object
Arthur Ulfeldt
  • 90,827
  • 27
  • 201
  • 284
  • Thanks Arthur for steady reply. I tried steps mentioned above and in provided tutorial. But somewhere it is breaking. Details - I have created separate Java type project and in the same I am specifying path as path = 'C:/Workdesk/Java/Eclips~1/LearningClojure/clojure-test/src/test/clojure/clojure.mysql.clj' (This clojure.mysql.clj file is in separate project). After hitting run I am getting error - Could not locate Clojure resource on classpath: C:\Workdesk\Java\Eclips~1\LearningClojure\clojure-test\src\test\clojure\clojure.mysql.clj. Any clue. – user2108042 Feb 26 '13 at 16:54
  • If your clojure is in a seperate project It is sometimes easier to build a jar file for that project (this will include the .clj files by default) and include that jar file in the project you want to consume your clojure code. (assuming maven handles your classpath) – Arthur Ulfeldt Feb 26 '13 at 18:44
  • Hi Arthur, I am badly stuck as I am getting "Could not locate Clojure resource on classpath" error again and again. Meanwhile I have posted complete information [here](http://stackoverflow.com/questions/15116334/could-not-locate-clojure-resource-on-classpath). – user2108042 Feb 27 '13 at 15:53
0

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.

mikera
  • 105,238
  • 25
  • 256
  • 415