Passing common types between Java and (Rhino) Javascript

Viewed 13107

I'm unclear on the rules for how types are converted between Javascript and Java when using (Mozilla) Rhino.

There's some specifics in the documentation about String:

It's important to keep in mind that Java strings and JavaScript strings are not the same […]Rhino provides some help in reducing the differences between the two types. First, you can pass a JavaScript string to a Java method that requires a Java string and Rhino will perform the conversion. We actually saw this feature in action on the call to the java.lang.String constructor in the preceding example. Rhino also makes the JavaScript methods available to Java strings if the java.lang.String class doesn't already define them

But what about others? If I pass a javascript Number to a Java method expecting int, double (or Integer or Double) will it get converted? What about long/Long? (which won't fit in a Double and so won't fit in a JS number?

What about Java methods returning these values?

Then there's Boolean/boolean. Are the JS constants true and false converted to and from the appropriate Java value? I've seen code like

java.lang.Boolean.TRUE.booleanValue()

used from JS, so at least some people think it isn't.

I have looked at the Mozilla Rhino documentation but do point out if I've missed something obvious.

3 Answers

This was solved by having the wrapper factory do the work for me in the situations where string doesn't implement all of the addons that js string has (like how string.length !== string.length() )

This can be set at the top level with:

context = Context.enter();

//This tells Rhino to convert String, Number, Boolean and Character into their JavaScript equivalents when returning from a Java function
context.getWrapFactory().setJavaPrimitiveWrap(false);

context.initStandardObjects();
Related