Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  167] [ 1]  / answers: 1 / hits: 23415  / 13 Years ago, fri, january 13, 2012, 12:00:00

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 recognized: https://stackoverflow.com/a/1433489/975097



How can I get the NativeArray type to be recognized?


More From » java

 Answers
6

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]

[#88035] Thursday, January 12, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;