JavaScriptingAPI
调用JavaScriptingAPI,java,javascript,api,Java,Javascript,Api,调用callScriptFunction()时,它显示scriptReturnValue为null。如何重写函数以避免空值 public class SimpleInvokeScript { public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException { new SimpleInvokeScri
callScriptFunction()
时,它显示scriptReturnValue为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";
}
}
js将如下所示。另外,我还有一个疑问,我给出了msg=myJavaApp.getSpecialMessage()
,没有var声明,它正在工作。我们可以避免var声明吗
function scriptFunction(name){
var msg = myJavaApp.getSpecialMessage();
println( msg );
}
JavaScript代码不包含
return
语句,因此它不会向Java代码返回值。这就是为什么Java端的返回值为null。你希望它返回什么?我想返回消息,我给出了类似“return msg”的返回语句,但它仍然显示相同的null问题。你知道问题是将数据传递到JavaScript还是从JavaScript获取数据?考虑一下用JavaScript中的硬编码字符串来测试这个问题,如<代码> var MSG =“嗨妈妈!”;<代码>。如果这样做有效,那么您就知道问题在于Java没有传递您的消息。