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

tirithen picture tirithen · Oct 29, 2010 · Viewed 12.3k times · Source

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.

Answer

Greg Hewgill picture Greg Hewgill · Nov 12, 2010

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.