Anderson Green Anderson Green - 2 years ago 154
Java Question

Converting a Javascript array to a Java array

I'm trying to convert a Javascript array in Java to a Java array. I'm using the javax.script package.
I tested this example here, but the type "NativeArray" was not recognized:

How can I get the NativeArray type to be recognized?

Answer Source

Per this answer it looks like your best bet is to write a JavaScript converter function which transforms the native JavaScript array into a Java array using Rhino's Java binding functionality. Note that you'll have to take some care to use the correct type when converting the individual elements.

[Edit] Here's a working example using a string array:

ScriptEngine js = new ScriptEngineManager().getEngineByName("JavaScript");
String ss[] = (String[]) js.eval(
    "(function() {" +
    "  var a = java.lang.reflect.Array.newInstance(java.lang.String, 3);" +
    "  a[0] = 'foo';" +
    "  a[1] = 'bar';" +
    "  a[2] = 'gah';" +
    "  return a;" +
System.out.println(Arrays.toString(ss)); // => [foo, bar, gah]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download