Using a ScriptEngine and Bindings, it seems that it treats the variables going in as Java Strings instead of JavaScript strings. The languages have member functions with identical signatures but different behaviors, and this creates quite a bit of confusion when writing scriptlets. I would like the Java functions to not be available, passing the bindings as if they were JavaScript string literals, forcing use of only JavaScript functions.
I have tried using the --no-java arg, which it is accepting, but doesn't seem to be doing what I thought it would. I have also tried using a ClassFilter to accomplish the same thing, to no avail.
In the below example, I would like to get an exception for an undefined method (replaceAll is only in Java, not in JavaScript). Instead it prints Qonald Quck.
package test;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
import jdk.nashorn.api.scripting.ClassFilter;
public class TestScripting {
public static void main(String[] args) throws ScriptException {
System.getProperties().setProperty("nashorn.args", "--no-java");
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine jsEngine = factory.getScriptEngine(new ClassFilter() {
@Override
public boolean exposeToScripts(String arg0) {
return false;
}
});
Bindings bindings = jsEngine.createBindings();
bindings.put("MyString", "Donald Duck");
String res = (String) jsEngine.eval("MyString.replaceAll('D','Q')",
bindings);
System.out.println(res);
}
}
The truth is that internally, Nashorn uses java.lang.String
to represent the JavaScript primitive string
type. However, since we reckoned some people would be annoyed if they couldn't invoke Java String
methods on them, we also allow that. (The same treatment goes for java.lang.Boolean
, java.lang.Integer
, and java.lang.Double
which are also internal representation of JS primitive types boolean
and number
.)
It seems reasonable though that --no-java
should disable this. I filed this as an issue.