I want to expose a Java method so that it can be called by arbitrary scripts. The script should then be able to perform arithmetic operations on the return value.
The problem is that although the exposed method returns a Java Integer
, the script does not actually get a regular number, but an instance of org.mozilla.javascript.NativeJavaObject
.
Here is some simplified test code that shows the behaviour:
public class RhinoTest
{
public static void main(String[] args)
{
String script = "foo.getBar() + 1";
Context context = Context.enter();
ScriptableObject scriptableObject = context.initStandardObjects();
ScriptableObject.putProperty(scriptableObject, "foo", new Foo());
Object result = context.evaluateString(scriptableObject, script, "FooBar", 1, null);
Context.exit();
System.out.println(result);
}
public static class Foo
{
public Integer getBar()
{
return 9;
}
}
}
The expected result is 10
, but the script returns 91
.
So how can I make getBar()
calls happening inside the script actually return a regular Javascript data type? Please note that I don't want to alter the script code by adding unwrap()
calls, parseint()
or the like.
Modify your context WrapFactory:
context.getWrapFactory()
.setJavaPrimitiveWrap(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With