Zuriar
Zuriar

Reputation: 11784

Using a Java class in the clojure repl

I have the following Java class:

public class Speak {
   public static String greet() {
     return "Hello! I am a human!";
   }
}

I have compiled this to Speak.class

How do I now import it into the clojure repl and how do classpaths and namespaces fit in?

Thanks

Upvotes: 0

Views: 741

Answers (1)

GregA100k
GregA100k

Reputation: 1395

With the standard clojure repl, the class file needs to be available on the classpath used to start the repl. Here's an example

java -cp pathToClojure\clojure.jar;.\src;.\lib;.\lib\* clojure.main %1

I have the src included for clojure source, the lib folder included for class files, and lib* included for classes included in jar files.

In this example, the Speak class can be included and used with:

user=> (import Speak)
Speak
user=> (Speak/greet)
"Hello! I am a human!"

This assumes that you have set up the classpath before starting the repl. If you want to add something to the classpath after the repl is started it's more complicated. Example code to do it can be found here

Upvotes: 2

Related Questions