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.
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.
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.
My code is as follows :-
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\")");
The doSomething method is called correctly, but it can't find endsWith :-
__EXCEPTION__:javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function endsWith.
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.
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... :(
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 ?
Thanks ! :)