简体   繁体   中英

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.

试试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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM