Java Reference
In-Depth Information
// Pass a JavaScript array to the PrintArray.print(String[] list) method
pa.print(names);
Inside print(String[] list):3
Rhino
Nashorn
JRuby
Nashorn supports array type conversions between Java and Nashorn arrays using the
Java.to()
and
Java.from()
methods. The
Java.to()
method converts a Nashorn array
type to a Java array type; it takes the array object as the first argument and the target Java
array type as the second argument. The target array type can be specified as a string or a
type object. The following snippet of code converts a Nashorn array to a Java
String[]
:
// Create a JavaScript array and populate it with three integers
var personIds = [100, 200, 300];
// Convert the JavaScript integer array to Java String[]
var JavaStringArray = Java.to(personIds, "java.lang.String[]")
If the second argument in the
Java.to()
function is omitted, the Nashorn array is
converted to a Java
Object[]
.
The
Java.from()
method converts a Java array type to a Nashorn array. The method
takes the Java array as an argument. The following snippet of code shows how to convert
a Java
int[]
to a JavaScript array:
// Create a Java int[]
var IntArray = Java.type("int[]");
var personIds = new IntArray(3);
personIds[0] = 100;
personIds[1] = 200;
personIds[2] = 300;
// Convert the Java int[] array to a Nashorn array
var jsArray = Java.from(personIds);
// Print the elements in the Nashorn array
for(var i = 0; i < jsArray.length; i++) {
print(jsArray[i]);
}
100
200
300
Search WWH ::
Custom Search