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.
Try clojure.lang.Compiler.loadFile(String file)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With