How to convert Rhino-JavaScript arrays to Java-Arrays

Viewed 26267

I have the following:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
jsEngine.eval("function getArray() {return [1,2,3,4,5];};");
Object result = jsEngine.eval("getArray();");

How can i convert the result object which is of type sun.org.mozilla.javascript.internal.NativeArray to a corresponding java array? Can somone show me a working code sample where this is done? It should work for String and Integer arrays. Plus, it would be great to know where to look for other data type conversions between the rhino engine and java.

Btw, i know this page but i'm really looking for a working code sample.

5 Answers

I'm not sure if it was the case when this question was first asked, but NativeArray implements the java.util.List interface. A simple way to convert to a real Java array is therefore:

Object[] array = ((List<?>) result).toArray();

In my case I wanted to produce a Java array within the script. (This use case also matches the question.)

Following Creating Java Arrays, I came up with

var javaArray = java.lang.reflect.Array.newInstance(java.lang.Integer, jsArray.length);
for (var i = 0; i < javaArray.length; i++) {
  javaArray[i] = new java.lang.Integer(jsArray[i]);
}
Related