Reputation: 107
I would like to call a static method in a Java class I have created from Clojure. How would I go about doing so?
What I have tried so far is simply creating a Java class in the same folder as my Clojure source, but either I am given a ClassNotFoundException or I am told that there is no such namespace. I have also attempted importing the class in various different ways, ending up redifining the Java package declaration several times with no further result.
I am using Leiningen for handling my Clojure project.
Upvotes: 2
Views: 325
Reputation: 841
You must also give information about the location of your Java class in the project.clj file of your project.
Here's an example.
The Java class:
public class BestClass {
public static String testThis() {
return "Hello";
}
}
This class is located in use-java\src\java
where use-java
is the project directory.
project.clj
:
(defproject use-java "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]]
:java-source-paths ["src/java/"]
:main ^:skip-aot use-java.core
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
The important part in the file above is :java-source-paths ["src/java/"]
.
Note that you can change the location of the class but :java-source-paths must be changed accordingly.
core.clj
:
(ns use-java.core
(:import BestClass))
(defn try-out-java-method []
(BestClass/testThis))
Calling try-out-java-method
gives:
use-java.core> (try-out-java-method)
"Hello"
Upvotes: 2