When I invoked the callScriptFunction()
it shows the scriptReturnValue is null. How can I rewrite the function to avoid the null?
public class SimpleInvokeScript {
public static void main(String[] args)
throws FileNotFoundException, ScriptException, NoSuchMethodException
{
new SimpleInvokeScript().run();
}
public void run() throws FileNotFoundException, ScriptException, NoSuchMethodException {
ScriptEngineManager scriptEngineMgr = new ScriptEngineManager();
ScriptEngine jsEngine = scriptEngineMgr.getEngineByName("JavaScript");
jsEngine.put("myJavaApp", this);
File scriptFile = new File("src/main/scripts/JavaScript.js");
// Capture the script engine's stdout in a StringWriter.
StringWriter scriptOutput = new StringWriter();
jsEngine.getContext().setWriter(new PrintWriter(scriptOutput));
Object scriptReturnValue = jsEngine.eval(new FileReader(scriptFile));
if ( scriptReturnValue == null) {
System.out.println("Script returned null");
} else {
System.out.println(
"Script returned type " + scriptReturnValue.getClass().getName() +
", with string value '" + scriptReturnValue + "'"
);
}
Invocable invocableEngine = (Invocable) jsEngine;
System.out.println("Calling 'invokeFunction' on the engine");
invocableEngine.invokeFunction("callScriptFunction", "name");
System.out.println("Script output:\n----------\n" + scriptOutput);
System.out.println("----------");
/** Method to be invoked from the script to return a string. */
public String getSpecialMessage() {
System.out.println("Java method 'getSpecialMessage' invoked");
return "A special announcement from SimpleInvokeScript Java app";
}
}
The JavaScript.js will look like this. Also, I have one more doubt, I gave msg = myJavaApp.getSpecialMessage()
without var declaration and it's working. Can we avoid var declaration?
function scriptFunction(name){
var msg = myJavaApp.getSpecialMessage();
println( msg );
}