Passing Java lists into JS

A. Sundararajan sundararajan.athijegannathan at oracle.com
Thu Nov 27 10:56:00 UTC 2014


List return values from Java are not converted to JS Arrays. But usual 
'indexing' to get elements and ".length" to get size work (later added 
in 8u20 or 8u40 - need to check). And usual for..in and for..each..in 
(extension) work on Lists. Rational is to avoid wrapping Lists as 
another Script object.


-Sundar

Tim Fox wrote:
> Hello again,
>
> I am a bit confused about how Lists passed from Java into JS are 
> converted.
>
> I have a Java class as follows:
>
> public class SomeClass {
>
>    public List<String> provideList() {
>      List<String> list = new ArrayList<>();
>      list.add("foo");
>      list.add("bar");
>      return list;
>    }
> }
>
> I call this from JavaScript:
>
> var io = Packages.io;
> var someObject = new io.vertx.scratchpad.SomeClass();
>
> var arr = someObject.provideList();
>
> console.log(arr[0]); // prints: foo
> console.log(typeof arr.length); // undefined
> console.log(arr instanceof Array); // false
>
> I was under the impression that Nashorn automatically converted Java 
> lists passed into JS into JS Arrays.
>
> The object arr returned in some ways resembles a JavaScript array - 
> the operators [] and []= work on it, however it doesn't have the array 
> property "length" and it's not an instanceof Array.
>
> Can anyone clarify to me what this object is? Any reason why Nashorn 
> doesn't just wrap it as a real JS Array?
>
> Cheers





More information about the nashorn-dev mailing list