views:

84

answers:

2

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.

+1  A: 

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.

Hamza Yerlikaya
Thanks Hamza, but I'm calling this from **Java**. I'd like to be able to do an eval. But without docs I simply don't know where the `eval` method is. (its not in clojure.lang.RT - I checked)
brice
[Edit:] Wait, I think I get you. Do you mean write a clojure file in a known location, and pass it the content of the clojure file that I want interpreted as an arg, so that it returns what I want. Is there no simpler way?
brice
+3  A: 

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

Stuart Sierra
That's it. Thanks Stuart!
brice
Would it be appropriate for me to add this to the clojure wiki?
brice