Reputation: 41
I have a javascript file fun.js
function fun1(){
var str='apple';
var charArray = Array.from(str);
return charArray;
}
I return this charArray to my java code using nashorn. But nashorn gives exception as-
javax.script.ScriptException: TypeError: Array.from is not a function in at line number 25
How can I use Array.from() with nashorn or is there any way to convert string to charArray in js which is compatible with nashorn.
my java code is -
System.out.println("intialising parser....");
ScriptEngine engine= new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("index.js"));
Invocable invocable= (Invocable) engine;
Object obj = (Object)invocable.invokeFunction("fun1");
Upvotes: 1
Views: 958
Reputation: 41
Later I found it was simple like this-
function fun1(){
var str='apple';
var charArray =str.split('');
return charArray;
}
Also it is compatible with nashorn.
Upvotes: 0
Reputation: 201447
There is, it is String.toCharArray()
, because Nashorn allows you to use Java methods. So you can do,
System.out.println("initializing parser....");
String js = "function fun1() { return 'apple'.toCharArray() }";
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(js);
Invocable invocable = (Invocable) engine;
Object obj = (Object) invocable.invokeFunction("fun1");
System.out.println(Arrays.toString((char[]) obj));
} catch (Exception e) {
e.printStackTrace();
}
And that outputs
initializing parser....
[a, p, p, l, e]
Upvotes: 1