Narhon returns native JavaScript objects?

I am currently using the javax implementation for Rhino. By default, Rhino uses a wrapper to return Java objects. Does Nashorn have this behavior or does it return JavaScript objects by default?

thanks

+4
source share
2 answers

He seems to be trying his best to recover intelligent objects. Using this code, change 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()); 

Productivity:

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

It seems that although Java objects can be used in JS code, it still refers to Java objects (although they appear as function objects, so there should be a wrapper), we cannot consider 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 is the result:

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

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

* If you want to test the code above more easily, just create an alias for your JDK jjs (Nashorn Interpreter), for example, 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 named "JAVA8_HOME" and point to your jdk8 folder, then you can call jjs by running the following command:

 > "%JAVA8_HOME%\jre\bin\jjs" test.js 
+1
source

Source: https://habr.com/ru/post/1487792/


All Articles