Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package jsr223;
import javax.script.*;
public class MultiScopes {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("Clojure");
engine.put("x", "Mark");
// print global variable "x"
engine.eval("(println x)");
engine.eval("(defn say-hello [bar] (println (str \"Hello \" bar)))");
engine.eval("(say-hello x)");
engine.eval(new InputStreamReader(MultiScopes.class.getResourceAsStream("/testing.clj")));
engine.eval("(testing/say-hello-from-testing x)");
Object value = engine.eval("(+ 5 6)");
System.out.println("Value is " + value);
System.out.println("Value's class is " + value.getClass().getName());
// Now, pass a different script context
ScriptContext newContext = new SimpleScriptContext();
Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
// add new variable "x" to the new engineScope
engineScope.put("x", "world");
// execute the same script - but this time pass a different script context
engine.eval("(println *clojure-version*)", newContext);
engine.eval("(println *ns*)", newContext);
engine.eval("(println user/x)", newContext);
engine.eval("(say-hello x)", newContext);
// the above line prints "world"
manager.getEngineByName("Clojure").eval("(say-hello x)", newContext);
Hello Mark
Hello there Mark, how are you?
Value is 11
Value's class is java.lang.Long
{:major 1, :minor 3, :incremental 0, :qualifier alpha4}
#<Namespace user>
Hello world
Hello world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment