を呼び出す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 は次のようになります。また、もう1つ疑問がありますmsg = myJavaApp.getSpecialMessage()
。var宣言なしで指定しましたが、機能しています。var 宣言を避けることはできますか?
function scriptFunction(name){
var msg = myJavaApp.getSpecialMessage();
println( msg );
}