3
votes

My Leiningen project requires a few external Java classes that I am trying to access from Clojure.

At first I tried putting the class files in my_project/resources/ since this directory is on the classpath which is confirmed by running

lein classpath

However, I couldn't access even a simple toy Java class from Clojure which resides in said directory. To keep things as simple as possible, my toy class does not have a package declaration.

My second approach involved adding a :java-source-path key to my project.clj, but I was again struck by failure (same behaviour as above, I can't access the class from a Clojure REPL).

Where am I going wrong here?

4

4 Answers

2
votes

Couple of things that could be wrong:

Are you using .class files or .java files? java-source-path is for sources, that is, .java files. And .java files need to be compiled before they can be loaded.

Also, java classes need to be either imported or qualified with their full package name in clojure code.

If possible and your java code isn't directly tied to the clojure stuff, it's easiest to just have your java files compiled and bundled in a jar that you can add to the dependencies of your leiningen project.

0
votes

After putting the java source in the path, did you run lein compile?

0
votes

In your .project file for your project specify the :java-source-paths as ["java"] and not "java"1 if the "java" directory is where you put the java source files in your project's directory.

Running 'lein run' should auto compile java sources before actually running if you've specified the :java-source-paths and :main right in your .project file.

Source: https://github.com/technomancy/leiningen/blob/master/doc/MIXED_PROJECTS.md

  1. I made this mistake and kept wondering what I was doing wrong. The Chas Emerick Clojure programming book in the relational database chapter that talks about hibernate needs to be updated a bit.
0
votes

In your project.clj do you have a keyword for your resource paths? You said you have the java-source-paths keyword, but those are used for .java files that need to be compiled when your project is built / ran. In your project.clj file add this

:resource-paths ["relative/path/to/your/classes/folder" "relative/path/to/other/classes"]

This will allow your project to reference your various classes with an import statement in your namespace declaration.

(ns my.project.name-space
  (:require [clojure.core.async :as async])
  (:import MySuperAwesomeClass))