How can I access Java String methods from a String variable passed to JavaScript?
<p>I'm using the Java Scripting Engine (in Java 1.6) to dynamically evaluate some expressions in my Java program. I can pass my Java objects from Java to JavaScript, and call their methods, but this stops working correctly when I pass String objects.</p>

<p>For example, in my Java I can define a class, JavaClass, with a doSomething method.
I can then call the doSomething method when I pass a JavaClass object to JavaSCript.</p>

<p>However, if I make a String object in Java, and pass it to JavaScript, I get an error when I try to call the endsWith method on it, in JavaScript.</p>

<p>My code is as follows :-</p>

<pre><code>ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String myString = "apple hello";
JavaClass javaClass = new JavaClass();
engine.put("myString", myString);
engine.put("thing", javaClass);
engine.eval("thing.doSomething()");
engine.eval("myString.endsWith(\"hello\")");
</code></pre>

<p>The doSomething method is called correctly, but it can't find endsWith :-</p>

<pre><code>__EXCEPTION__:javax.script.ScriptException:   sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function endsWith. 
</code></pre>

<p>It's as if my Java String object gets converted to a JavaScript string object - I can use the length property of a JavaScript String, for instance.</p>

<p>I can add my own endsWith function to my JavaClass class, which simply calls the String endsWith, and this works correctly - but is not nice... :(</p>

<p>If it is being converted, can I stop this happening ?
If it's something else, am I doing something wrong ? Is there a way to fix it ?</p>

<p>Thanks ! :)</p>
