I am utilizing the javax.scripting with Rhino in this project.
I have a Java method that returns a Java Object (Double, Long, Integer, etc). I want to call that
I developed this application where you enter a set of mathematical formulas that will be evaluated by the JavaScript engine built into Java 6, which I believe is a port of rhino. The idea was that we would have a set of maps and these maps would contain variables, such as:
MAP["VALUE 1"]
MAP["VALUE 2"]
I used that approach as some of the expressions for the formulas came from variables that were under my control and that could be invalid JS identifiers. My first approach was to declare a map and add it to the JS engine, but it failed in the same way that it's failing with you - it was interpreting it as a string, and not as a number.
The solution was to parse the formula, figure out what variables are being used by it, and then declare the object inside the JS engine.
Something like this:
var MAP = new Object();
MAP["VALUE 1"] = 1;
MAP["VALUE 2"] = 2;
And thenMAP["VALUE 1"] + MAP["VALUE 2"]
will return 3
, and not 12
.
There may be a better solution around, but once you go around the initial coding/ parsing, the above will always work. In our case there's a phase where we execute the "declarative" statements, and another phase where we execute the formulas. The JS engine is REALLY fast, so it's not a problem for us.
Use the following as the output in your JavaScript code :
function aFunction(data)
{
return parseInt(data);
}
Try the following
public static void main(String [] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName ("rhino");
data data = new data();
Context.enter().getWrapFactory().setJavaPrimitiveWrap(false);
try
{
engine.eval("function test(data) { return data.get('value1') + 5;};");
System.out.println("Result:" + ((Invocable)engine).invokeFunction("test", data));
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static class data
{
Double value = 1.0d;
public Number get(String arg) { return value; }
}
Alternatively, you could modify the javascript function to explicitly cast the value to a number:
function test(data) { return parseInt(data.get('value1'), 10) + 5;}