问题
I'm writing a high-performance nashorn application, and what I'd really like to do is find something equivalent to new String[]{"foo", "bar", "noise"}
from within javascript. The cost of converting from a javascript array to a java array is prohibitively expensive, shows up on every flame graph.
The best I've found up to this point is:
{var StringArray = Java.type('java.lang.String[]');"); var arr = new StringArray(3)); var arr[0] = 'foo'; var arr[1] = 'bar'; var arr[2] = 'noise'; arr;
}
But that's super ugly. Is this the best syntax available to me?
Thanks!
回答1:
You can do this using Java.to()
:
Java.to(["foo", "bar", "noise"],"java.lang.String[]");
If this code works for you (it does for me, tested with jjs 1.8.0_51), you can create a function to ease the code readability. Like this:
function toJavaStringArray(a) {
return Java.to(a,"java.lang.String[]");
}
来源:https://stackoverflow.com/questions/32193667/new-java-array-of-strings-in-nashorn