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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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)
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.