Question

I'm currently using the javax implementation of Rhino. By default Rhino uses a wrapper to return Java objects. Does Nashorn have similar behaviour or does it return JavaScript objects by default?

Thanks

Was it helpful?

Solution

Looks like it tries its best to return sensible objects. Using this code, then changing the XXX:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("nashorn");
engine.eval("function test() { return XXX; };");
Object result = ((Invocable)engine).invokeFunction("test");
System.out.println(result.getClass().getName());

Yields:

return 'hello world' = java.lang.String
return 1 = java.lang.Integer
return { name: 'Hello' } = jdk.nashorn.api.scripting.ScriptObjectMirror

OTHER TIPS

Looks like that, even though the Java objects can be used within the JS code, it still references Java Objects (although they show up as function objects so there must be a wrapper there), we can't treat them as Javascript objects:

//"import"
var StringTokenizer = java.util.StringTokenizer;

print(typeof StringTokenizer);

var st = new StringTokenizer("this is a test");

print(typeof st);
java.util.StringTokenizer.prototype.name = 'myST';

print(st.name);

And here's the result:

testObj.js:9 TypeError: Cannot set property "name" of undefined

Now Javascript objects will be loaded as "jdk.nashorn.internal.scripts.JO" instances.

*If you want to test the above code more easily, just create an alias for your JDK's jjs (Nashorn Interpreter), e.g., if you create a file called test.js, you can run the program with:

$ jjs test.js

Mac OS = alias jjs=’/Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/jre/bin/jjs’

Windows = Define an environment variable called ‘JAVA8_HOME’ and point to your jdk8 folder, then you can invoke jjs by running this command:

> “%JAVA8_HOME%\jre\bin\jjs” test.js
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top