1

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 ! :)

1 Answer 1

1

Change the last line to this. By default Strings are converted between Java and JS types automatically. Hence, you must forcefully convert myString into a Java string within your JS code..

    engine.eval("new java.lang.String(myString).endsWith(\"hello\")");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.