Search code examples
javascriptjavanashorn

Java - ScriptEngineManager nashorn Math.random does not work


i call the follow function with the functionName "random" and the parameter "1 and 50".

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;
    }

The content of random.js looks like:

  function random(min, max){
    return  Math.floor(Math.random() * (max - min +1)) + min;
  }

The results are never between 1 and 50. It is always more than 100.

If i use it not in java it works. Work math from nashorn/javascript oherwise in java?

UPDATE:

My solution is:

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;
}

So i can use parameters with different types.


Solution

  • Adding to Elliot's example there must be something wrong with the parameters you are passing in. The following also generates 100 values between 1 and 50.

    public static void main(String[] ar) {
        String script = "function random(min, max) { "
                + "return Math.floor(Math.random() * (max - min + 1)) + min; }";
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        Invocable invocable = (Invocable)engine;
        try {
            engine.eval(script);
            for (int i = 0; i < 100; i++) {
                Double result = (Double)invocable.invokeFunction("random", 1, 50);
                System.out.println(result.intValue());
            }
        } catch (ScriptException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }