Java Reference
In-Depth Information
Using Java Arrays
The way Java arrays can be created in JavaScript differs in Rhino and Nashorn. In Rhino,
you need to create a Java array using the newInstance() static method of the java.lang.
reflect.Array class. This syntax is also supported in Nashorn. The following snippet of
code shows how to create and access Java arrays using the Rhino syntax:
// Create a java.lang.String array of 2 elements, populate it, and print
// the elements. In Rhino, you were able to use java.lang.String as
// the first argument, but in Nashorn, you need to use
// java.lang.String.class instead.
var strArray = java.lang.reflect.Array.newInstance(java.lang.String.class, 2);
strArray[0] = "Hello";
strArray[1] = "Array";
for(var i = 0; i < strArray.length; i++) {
print(strArray[i]);
}
Hello
Array
To create primitive type arrays such as int , double , and so on, you need to use their
TYPE constants for their corresponding wrapper classes, as shown:
// Create an int array of 2 elements, populate it, and print the elements
var intArray = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE, 2);
intArray[0] = 100;
intArray[1] = 200;
for(var i = 0; i < intArray.length; i++) {
print(intArray[i]);
}
100
200
 
Search WWH ::




Custom Search