Defining default / global Java object for Nashorn script engine?
With the Java Nashorn script engine, I can provide objects in the context of an eval () using bindings like:
Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("rules", myObj);
scriptEngine.eval("rules.someMethod('Hello')", scriptContext);
I would like to be able to simplify the javascript by providing a default object so that instead of javascript it will be:
rules.someMethod('Hello')
I can just write:
someMethod('Hello')
Is there a way to do this? (someMethod is an object method, not a static method)
+3
source to share
1 answer
You can use the Object.bindProperties nashorn extension to bind properties of an arbitrary object to a global JS object. This way, the user can call methods (and accessor properties) on their default object from the script without qualifications. See Object.bindProperties documentation here https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Object.bindProperties
Sample code:
import javax.script.*;
public class Main {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
// get JavaScript "global" object
Object global = e.eval("this");
// get JS "Object" constructor object
Object jsObject = e.eval("Object");
Invocable invocable = (Invocable)e;
// calling Object.bindProperties(global, "hello");
// which will "bind" properties of "hello" String object
// to JS global object
invocable.invokeMethod(jsObject, "bindProperties", global, "hello");
// you're calling "hello".toUpperCase()"
e.eval("print(toUpperCase())");
// accessing bean property "empty" on 'hello' object
e.eval("print(empty)");
// just print all (enumerable) properties of global
// you'll see methods, properties of String class
// (which'd be called on "hello" instance when accessed)
e.eval("for (var i in this) print(i)");
}
}
+6
source to share