Converting a Javascript array to a Java array

前端 未结 4 1184
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-20 17:38

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 reco

4条回答
  •  醉梦人生
    2021-01-20 18:01

    Rhino offers this:

    https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Embedding_tutorial#usingJSObjs

    Also Scriptable interface offers get() and set() so you can easily enumerate the properties of an object and add it to an array:

    Scriptable arr = (Scriptable) result;
    Object [] array = new Object[arr.getIds().length];
    for (Object o : arr.getIds()) {
       int index = (Integer) o;
       array[index] = arr.get(index, null);
    }
    

    Same thing but not using NativeArray since that appears to be a Rhino specific thing. You could easily drop a breakpoint and see what type of object you were given then downcast to that. It's some sort of JS Array implementation that's pretty close to NativeArray.

提交回复
热议问题