我使用functionName「random」和參數「1和50」調用跟隨函數。Java - ScriptEngineManager nashorn Math.random不起作用
private String callFunction(String functionName, String[] parameter)
throws FileNotFoundException, ScriptException, NoSuchMethodException {
ScriptEngineManager engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader(myPath + functionName + ".js"));
Invocable invocable = (Invocable) engine;
Object result;
if (parameter == null) {
result = invocable.invokeFunction(functionName);
} else {
result = invocable.invokeFunction(functionName, parameter);
}
System.out.println(result);
return (String) result;
}
random.js的內容是這樣的:
function random(min, max){
return Math.floor(Math.random() * (max - min +1)) + min;
}
的結果是從來沒有1到50之間總是超過100
如果我在java中不使用它有用。 在java中從nashorn/javascript oherwise工作數學?
UPDATE:
我的解決辦法是:
private String callFunction(String functionName, String parameter)
throws FileNotFoundException, ScriptException, NoSuchMethodException, ClassCastException {
String result = "";
engine.eval(new FileReader(PropertiesHandler.getFullDynamicValuePath() + functionName + ".js"));
if (parameter == null) {
result = (String) engine.eval(functionName + "();");
} else {
result = (String) engine.eval(functionName + parameter + ";");
}
return (String) result;
}
所以我可以使用不同類型的參數。
是的,你有權利!我一直使用字符串參數!我認爲invokeFunction只能使用字符串。謝謝!!! – mscholz3