Java8 JS Nashorn convert array to Java array

user2053898 picture user2053898 · Mar 18, 2014 · Viewed 17.1k times · Source

How can I convert JS array to native array ? In Rhino conversion looked like (Scala code):

val eng = (new javax.script.ScriptEngineManager).getEngineByName("JavaScript")
val obj = eng.eval("[1,2,3,4]")
val arr = obj.asInstanceOf[sun.org.mozilla.javascript.internal.NativeArray]

In Nashorn NativeArray absent, and I can't find any documentation on conversion.

Answer

Attila Szegedi picture Attila Szegedi · Mar 19, 2014

From Java (and Scala), you can also invoke convert method on jdk.nashorn.api.scripting.ScriptUtils class. E.g. from Java:

import jdk.nashorn.api.scripting.ScriptUtils;
...
int[] iarr = (int[])ScriptUtils.convert(arr, int[].class)

my Scala is not too fluent, but I believe the equivalent is:

val iarr = ScriptUtils.convert(arr, Array[Int]).asInstanceOf(Array[Int])