Converting a Javascript array to a Java array

前端 未结 4 1200
爱一瞬间的悲伤
爱一瞬间的悲伤 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:25

    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]
    

提交回复
热议问题