Search code examples
javascriptjavaarraysnashorn

Nashorn - How to get a JS Array in Java?


I have this JS function:

function newJSArray() {return []}

That I am trying to return in Java using the following method:

public static NativeArray newArray() throws Exception {
    return (NativeArray)invocable.invokeFunction("newJSArray");
}

But it's throwing an exception when I try to invoke this function:

Exception in thread "main" java.lang.NoSuchMethodError: ....JavaScript.newArray()Ljdk/nashorn/api/scripting/JSObject;
    at ....

I want to be given a JS array specifically so I can call jsArr1.concat(jsArr2).


Solution

  • Yes, all API methods return JavaScript objects as instances of jdk.nashorn.api.scripting.JSObject. You can access members of that JS array by JSObject.getSlot method.