My most popular answer on Stack Overflow has to do with Clojure-Java interop. Since that answer was written, some of the tools used in the answer, specifically enclojure, have been deprecated. Because many of the follow-up questions related to how to build a working version of the answer, I thought it might be a good idea to update the post with modern tools.
As this is written, the tools used include:
These instructions are for Windows 7 64-bit. Instructions for other OS’s are similar.
First create a project and associated directory structure using Leiningen:
Now, change to the project directory.
In the project directory, open the project.clj file and edit it such that the contents are as shown below.
Now, make sure all of the dependencies (Clojure) are available.
You may see a message about downloading the Clojure jar at this point.
Now edit the Clojure file
C:\projects\com.domain.tiny\src\com\domain\tiny.clj such that it contains the following contents. (This file was created when Leiningen created the project.)
Much of the magic here is in the namespace declaration. The
:gen-class tells the system to create a class named
com.domain.tiny with a single static method called
binomial, a function taking two integer arguments and returning a double. There are two similarly named functions
binomial, a traditional Clojure function, and
-binomial and wrapper accessible from Java. Note the hyphen in the function name
-binomial. The default prefix is a hyphen, but it can be changed to something else if desired. The
-main function just makes a couple of calls to the binomial function to assure that we are getting the correct results. To do that, compile the class and run the program.
You should see output similar to the following:
Now package it up in a jar and put it someplace convenient. Copy the Clojure jar there too.
Leiningen has a built-in task,
lein-javac, that should be able to help with the Java compilation. Unfortunately, it seems to be broken in version 2.1.3. It can’t find the installed JDK and it can’t find the Maven repository. The paths to both have embedded spaces on my system. I assume that is the problem. Any Java IDE could handle the compilation and packaging too. But for this post, we’re going old school and doing it at the command line.
First create the file
Main.java with the following contents.
To compile java part
Now create a file with some meta-information to add to the jar we want to build. In
Manifest.txt, add the following text
Now package it all up into one big jar file.
To run the program:
The output is essentially identical to that produced by Clojure alone, but the result has been converted to a Java double.
As mentioned, a Java IDE will probably take care of the messy compilation arguments and the packaging.