Question

To evaluate a mathematical expression given in a String, I'm using the built-in JavaScript engine as explained in this answer:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
double result = (Double) engine.eval("Math.min(2, 4)");
// result: 2.0

It would be great if every function that belongs to Math (min, max, pow...) could be written without the Math. prefix, to lighten the expressions:

double result = (Double) engine.eval("min(2, 4)");

For now, I get the following exception:

sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "min" is not defined (<Unknown source>#1) in <Unknown source> at line number 1

Is there anyway to get this improvement done? For example, every time the exception gets catched, try to prefix the undefined reference by Math. and re-evaluate the expression? I've not been able to find how to proceed.

I tried to used the engine.put("min", ...) method, in vain.

Was it helpful?

Solution

One option would be to do something like

engine.eval("min = Math.min");
...

double result = (Double) engine.eval("min(2, 4)");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top