当我调用callScriptFunction()
时,它显示scriptReturnValue为null。如何重写函数以避免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";
}
}
JavaScript.js看起来像这样。另外,我还有一个疑问,我给了msg = myJavaApp.getSpecialMessage()
没有var声明,它正在工作。我们可以避免var声明吗?
function scriptFunction(name){
var msg = myJavaApp.getSpecialMessage();
println( msg );
}