Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I use Rhino return a string from Java to Javascript, all I get is org.mozilla.javascript.JavaNativeObject when I use

var jsString = new java.lang.String("test");

inside my js file.

Is this the right way to do it?

var jsString = String(new java.lang.String("test"));

The goal is to have a Java method to return the String object instead of creating it on the fly like above.

like image 309
tirithen Avatar asked Oct 29 '10 09:10

tirithen


3 Answers

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.

like image 159
Greg Hewgill Avatar answered Nov 15 '22 14:11

Greg Hewgill


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
like image 24
Brian Avatar answered Nov 15 '22 12:11

Brian


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);
like image 24
Rediska Avatar answered Nov 15 '22 13:11

Rediska