1

Let's say we have a Java project in IntelliJ Idea with La Clojure plugin installed and clojure.jar library imported as External Library.

I would like then to add a Clojure file.clj into our Java Project structure and use functions from this file for my further internal purposes.

How to create a clojure file in a Java project and then use clojure code from there? I've looked through a couple of variants but it didn't work for me or just wasn't enough. Even on YouTube there're plenty of dummy videos just showing how to run a repl but nothing about how to stick java and clojure together and turn this to easy, enjoyable and convinient programming discipline. For example:

input.clj:

(defn foo [a b] (str a " " b))

Hello.java

public class Hello {
    psvm {
            //invoke: (foo "Hello from file.clj")
    }
}

Update: Thanks for your help, just started using Clojure 1.6.0 and didn't expect it would be that easy.

/** Question: If I won't declare and init IFn, then Java throws "Exception
* in thread "main" java.lang.ExceptionInInitializerError" during an attempt
* to read the file. Why? And how not to use IFn if not really necessary?
*/
IFn require = Clojure.var("clojure.core", "require");

// Import file input.clj with a bunch of functions
clojure.lang.Compiler.loadFile("input.clj");

// Call foo
IFn foo = Clojure.var("clojure.core", "foo");
Object result = foo.invoke("Hi", "there");

// Feel good
System.out.println(result);
Happy Torturer
  • 1,128
  • 15
  • 27

2 Answers2

3

In addition to Steve's comment which is the correct answer to this question, note also that Cursive (based on an old fork of La Clojure, which is no longer under active development) provides support for these calls (both API and RT.var). You can navigate to the Clojure code from Java, Find Usages from Clojure will find the Java usages, and you have autocompletion in the Java strings. It really helps a lot when you have to use these forms. Full disclosure: I develop Cursive, I added all this because I use it a lot in Cursive itself.

Colin
  • 1,112
  • 2
  • 7
  • 16
1

If you're using Clojure 1.6 then look at https://stackoverflow.com/a/23555959/24396 and http://clojure.github.io/clojure/javadoc/clojure/java/api/package-summary.html

For Clojure 1.5 you'll have to use clojure.lang.RT

Community
  • 1
  • 1
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
  • Thanks, worked great for me. I also updated my question. Please check. If I won't declare and init IFn, then Java throws "Exception in thread "main" java.lang.ExceptionInInitializerError" during an attempt to read the file. Why? And how not to use IFn if not really necessary? – Happy Torturer Jul 13 '14 at 22:27