Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically load a Clojure script from outside of my classpath from java?

I wish to enable user defined Clojure scripts to interact with my Java App. The problem is, I don't know in advance where the Clojure scripts will be located, so I can't include them in my classpath when running the app.

How do I dynamically load a Clojure script from outside of my classpath?

I've tried the simple example:

RT.loadResourceScript("test.clj");
Var foo = RT.var("user", "foo");
Object result = foo.invoke("Hi", "there");
System.out.println(result);

with a test.clj that looks like:

(ns user)

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

But no luck.

I think it has something to do with RT.makeClassLoader() or RT.baseLoader() and using the returned loader to load the clojure file, but I cannot seem to make it work. (I keep getting ClassNotFound) I could probably muddle through the javadoc for the clojure.lang.RT, but I simply could not find them.

like image 403
brice Avatar asked Jul 30 '10 13:07

brice


2 Answers

Try clojure.lang.Compiler.loadFile(String file)

like image 149
Stuart Sierra Avatar answered Sep 23 '22 18:09

Stuart Sierra


As long as they depend on the stuff in your classpath what you can do is read the file as a string and evaluate it,

(def content "(ns user) (defn foo [a b] (str a \" \" b))")
(map eval (read-string (str \( content \))))

read-string read one object from the stream so you need to wrap everthing in a list to make it one object.

like image 45
Hamza Yerlikaya Avatar answered Sep 26 '22 18:09

Hamza Yerlikaya