Rhino: How to return a string from Java to Javascript?

In general, you would call Context.javaToJS which converts a Java object to its closest representation in Javascript. However, for String objects, that function returns the string itself without needing to wrap it. So if you're always returning a string, you don't need to do anything special.


Turn off the wrapping of Primitives and then the value returned in your expression will be a JS string:

Context cx = Context.enter();
cx.getWrapFactory().setJavaPrimitiveWrap(false);

Although in most cases the returned Java String type can be used just like the JS String type within the JS code, it does not have the same methods!

In particular I found it cannot be used in a JS object passed to 'stringify()' as it does not have the toJSON() method.

The only solution I found is to explicitly do the addition of "" in the JS, to convert the Java String to a JS String. I found no way to code the java method to return a good JS string directly... (as Context.javaToJS() doesn't convert a Java String) Eg:

var jstr = MyJavaObj.methodReturningAString();
JSON.stringify({ "toto":jstr});   // Fails
JSON.stringify({ "toto": ""+jstr});  // OK