Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rhino: How to return an Integer from Java method called by JavaScript?

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.

like image 539
Jens Bannmann Avatar asked Oct 21 '22 17:10

Jens Bannmann


1 Answers

Modify your context WrapFactory:

context.getWrapFactory()
       .setJavaPrimitiveWrap(false);
like image 108
McDowell Avatar answered Nov 03 '22 19:11

McDowell