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

2

5

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.

Rozanneroze answered 30/7, 2010 at 13:49 Comment(1)
Yeah... where's teh javadoc! #:/Hued
S
7

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

Swallowtailed answered 30/7, 2010 at 15:2 Comment(1)
Would it be appropriate for me to add this to the clojure wiki?Rozanneroze
T
1

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.

Tridentum answered 30/7, 2010 at 14:34 Comment(2)
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)Rozanneroze
[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?Rozanneroze

© 2022 - 2024 — McMap. All rights reserved.