How to convert Rhino-JavaScript arrays to Java-Arrays

旧街凉风 提交于 2019-11-27 22:04:51
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);
}

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();
Andrzej Doyle

If the Javascript is under your control, you could do the transformation there, as per this document. So to adapt your example, something like:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
jsEngine.eval("function getArray() {return [1,2,3,4,5];};");
String convertFuncSrc =
     "function convertArray(type, arr) {"
   + "  var jArr = java.lang.reflect.Array.newInstance(type, arr.length);"
   + "  for (var i = 0; i < arr.length; i++) { "
   + "    jArr[i] = arr[i];"
   + "  }"
   + "  return jArr;"
   + "};";
jsEngine.eval(convertFuncSrc);
Object result = jsEngine.eval("convertArray(java.lang.Integer.TYPE, getArray());");
int[] javaArray = (int[])result;

Although, if you can't change the Javascript this approach won't work, and you [i]will[/i] have an instance of sun.org.mozilla.javascript.internal.NativeArray as your result variable. At which point I think you just need to cast and deal with it directly, using whatever public methods it exposes; it's probably not pretty but I don't see any other options. In particular I think the only thing you can guarantee at the nice Rhino level is that it will be an instance of Scriptable (and probably ScriptableObject), which doesn't help you use it as an Array.

Kevin's answer looks like a good way to go here (and is similar to what I was just about to edit in! :-))

General solution using JASON as data intermediate:

Object result = jsEngine.eval("JSON.stringify(getArray())");    
JsonReader jsonReader = Json.createReader(new StringReader(result.toString()));
JsonArray jsonArray = jsonReader.readArray();
jsonReader.close();
int[] numbers = new int[jsonArray.size()];
int index = 0;
for(JsonValue value : jsonArray){
    numbers[index++] = Integer.parseInt(value.toString());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!