Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 JS Nashorn convert array to Java array

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.

like image 235
user2053898 Avatar asked Mar 18 '14 22:03

user2053898


2 Answers

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])
like image 194
Attila Szegedi Avatar answered Oct 12 '22 01:10

Attila Szegedi


Given a JavaScript array, you can convert it to a Java array using the Java.to() method in oracle nashorn engine which is available in jdk 8

Example

var data = [1,2,3,4,5,6];
var JavaArray = Java.to(data,"int[]");
print(JavaArray[0]+JavaArray[1]+JavaArray[2]);
like image 31
pardeep131085 Avatar answered Oct 12 '22 00:10

pardeep131085