How to convert Rhino-JavaScript arrays to Java-Arrays

Chris picture Chris · Sep 16, 2009 · Viewed 24.8k times · Source

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.

Answer

Kevin picture Kevin · Sep 16, 2009
NativeArray arr = (NativeArray) result;
Object [] array = new Object[(int) arr.getLength()];
for (Object o : arr.getIds()) {
    int index = (Integer) o;
    array[index] = arr.get(index, null);
}